Python。matplotlib。基于其他列的值(平行线)打印值

2024-10-02 12:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有下面的数据帧,我想要时间到x轴,vls和id到y轴。但是我想对行id进行分组,以查看separet行id及其对应的“vls”。到目前为止我用的是“groupby” '

df = pd.DataFrame({'vls': [ -22.0390625, -22.03515625, -27.0, -15.99609375, -10.984375, -12.9765625, -12.97265625, -19.9609375,-13.96484375, -19.95703125, -13.953125, -19.94921875, -21.9453125, -11.94140625, -21.9375, -21.93359375, -16.92578125, -13.921875, -12.91796875, -19.9140625, -10.91015625, -10.90625, -19.90234375, -10.8984375], 'id' : [1,2,3,4,5,4,5,5,5,4,3,3,4,4,4,2,1,5,5,3,5,2,5,5], 'time' : [51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74]})
g1 = df.groupby(["id"])
for i, data in g1:
    plt.plot(df.time, df.vls.values, label = i, linestyle=':', marker = 'o')
    plt.plot(df.time, df.id.values, linestyle=':', marker = 'o') 
plt.legend()

但我的输出是这样的:

enter image description here

但是我想得到5条单独的id线(应该是5条平行线)和5条“vls”线,它们不是顺序连接的,而是基于“id”列。 像这样: enter image description here


Tags: 数据iddftimeplot时间pltmarker
1条回答
网友
1楼 · 发布于 2024-10-02 12:38:53

您仍然在使用原始的数据帧,而您确实正确地使用了组。我认为你的意图如下:

from numpy import *
from matplotlib.pyplot import *
import pandas as pd
df = pd.DataFrame({'vls': [ -22.0390625, -22.03515625, -27.0, -15.99609375, -10.984375, -12.9765625, -12.97265625, -19.9609375,-13.96484375, -19.95703125, -13.953125, -19.94921875, -21.9453125, -11.94140625, -21.9375, -21.93359375, -16.92578125, -13.921875, -12.91796875, -19.9140625, -10.91015625, -10.90625, -19.90234375, -10.8984375], 'id' : [1,2,3,4,5,4,5,5,5,4,3,3,4,4,4,2,1,5,5,3,5,2,5,5], 'time' : [51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74]})
g1 = df.groupby(["id"])
fig, ax = subplots()
colors = cm.tab10(arange(len(set(df.id.values))+1))
for i, data in g1:
    ax.plot(data.time, data.vls.values, label = i, color = colors[i],linestyle=':', marker = 'o')
    ax.plot(data.time, data.id.values, linestyle=':', color = colors[i], marker = 'o') 
ax.legend()

编辑:添加了颜色匹配(不确定是否有意)

enter image description here

相关问题 更多 >

    热门问题