图中图例中的Pandas groupby对象

1l5u6lss  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(80)

我尝试使用代码fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i))绘制pandas 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()


当前打印


的数据

fkvaft9z

fkvaft9z1#

稍微整理一下数据:

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)


jxct1oxe

jxct1oxe2#

您可以使用groupby.SeriesGroupBy.plot而不是groupby.DataFrameGroupBy.plot将组名而不是列名作为图例。

from io import StringIO
import pandas as pd
import matplotlib.pyplot as plt

fp = StringIO("""
time,imei,battery
2016-09-30 07:01:23,862117024146766,42208
2016-09-30 07:06:23,862117024146766,42213
2016-09-30 07:11:23,862117024146766,42151
2016-09-30 07:16:23,862117995146745,42263
2016-09-30 07:21:23,862117995146745,42293
""")

df = pd.read_csv(fp)
df = df.set_index("time")

f, axes = plt.subplots(nrows=1, ncols=2, figsize=(16, 6))

# Original
df.groupby('imei').plot(
    y='battery', ax=axes[0], title="groupby.DataFrameGroupBy.plot"
)

# Solution
df.groupby('imei')['battery'].plot(
    ax=axes[1], title="groupby.SeriesGroupBy.plot", legend=True
)

字符串


的数据

相关问题