【问题标题】:python. matplotlib. plot values based on other column's values (parallel lines)Python。 matplotlib。根据其他列的值(平行线)绘制值
【发布时间】:2019-05-11 05:43:25
【问题描述】:

假设我有以下数据框,我想时间到 x 轴,vls 和 id 到 y 轴。但我想对线路 ID 进行分组,以查看分隔线 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()

但我的输出是这样的:

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

【问题讨论】:

    标签: python pandas matplotlib plot group-by


    【解决方案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()
    

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

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 2023-02-23
      • 1970-01-01
      • 2020-07-23
      相关资源
      最近更新 更多