【问题标题】:Pandas groupby object in legend on plot情节图例中的 Pandas groupby 对象
【发布时间】:2017-02-15 14:01:10
【问题描述】:

我正在尝试使用代码 fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i)) 绘制熊猫 groupby 对象

问题是情节图例将['battery']作为图例值。鉴于它为groupby 对象中的每个项目绘制一条线,因此在图例中绘制这些值更有意义。但是我不知道该怎么做。任何帮助将不胜感激。

数据

                 time             imei  battery_raw
0 2016-09-30 07:01:23  862117020146766        42208
1 2016-09-30 07:06:23  862117024146766        42213
2 2016-09-30 07:11:23  862117056146766        42151
3 2016-09-30 07:16:23  862117995146745        42263
4 2016-09-30 07:21:23  862117020146732        42293

完整代码

for i in entity:
    fil = df[(df['entity_id']==i)]
    fig, ax = plt.subplots(figsize=(18,6))
    fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i))  
    plt.legend(fil.imei)
    plt.show()

当前剧情

【问题讨论】:

  • 您能否发布一个示例数据框,用作 groupby 方法的输入?
  • 什么是fil.imei?如果你只做ax.legend()会发生什么?

标签: python pandas matplotlib plot


【解决方案1】:

稍微整理一下数据:

    date         time             imei      battery_raw
0 2016-09-30 07:01:23  862117020146766       42208
1 2016-09-30 07:06:23  862117020146766        42213
2 2016-09-30 07:11:23  862117020146766        42151
3 2016-09-30 07:16:23 862117995146745       42263
4 2016-09-30 07:21:23  862117995146745       42293

完整示例代码:

import matplotlib.pyplot as plt

fil = pd.read_csv('imei.csv', sep=r'\s*', engine='python')
fig, ax = plt.subplots(figsize=(18,6))

for name, group in fil.groupby('imei'):
    group.plot(x=pd.to_datetime(group['time']), y='battery_raw', ax=ax, label=name)

plt.show()

像往常一样,必须将 x 值转换为日期时间才能正确绘制。您也可以在数据框中执行此操作。

结果,由imei标记:

(注意:编辑以摆脱我第一次绊倒的奇怪之处。如果您将列表作为 y 参数传递给 group.plot,列表 ID 将用作行标签,大概是方便的默认值当您一次绘制多个因变量时。

#for name, group in fil.groupby('imei'):
#    group.plot(x=['time'], y=['battery_raw'], ax=ax, label=name)

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 2015-06-21
    • 2014-09-23
    • 1970-01-01
    • 2014-06-02
    • 2019-11-18
    相关资源
    最近更新 更多