蟒蛇 . matplotlib . 根据其他列的值绘制值(平行线)

让我说我有跟随数据帧,我想时间到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()

但我的输出是这样的:

但是我希望获得5个单独的id(应该是5条平行线)和5行'vls',它们不是连续连接,而是基于'id'列 . 像这样的东西:

回答(1)

2 years ago

您仍在使用原始数据框,而您确实正确使用了组 . 我认为您打算如下:

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()

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