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

时间:2018-12-10 10:27:39

标签: python pandas matplotlib plot group-by

让我说我有以下数据框,我想定时到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

但是我想为id获得5条单独的线(应该是5条平行线)和为'vls'获得5条线,这些线不是顺序连接,而是基于'id'列。 像这样的东西: enter image description here

1 个答案:

答案 0 :(得分:1)

您仍在使用原始数据框,而您并未正确使用组。我认为您打算这样做:

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