Python 在绘图上的图例中按对象分组

Python 在绘图上的图例中按对象分组,python,pandas,matplotlib,plot,Python,Pandas,Matplotlib,Plot,我正在尝试使用codefil.groupby('imei')来绘制pandasgroupby对象。绘图(x=['time'],y=['battery'],ax=ax,title=str(I)) 问题是绘图图例将['battery']列为图例值。鉴于它正在为groupby对象中的每个项目绘制一条线,因此在图例中绘制这些值更有意义。但是我不知道该怎么做。任何帮助都将不胜感激 资料 完整代码 for i in entity: fil = df[(df['entity_id']==i)]

我正在尝试使用code
fil.groupby('imei')来绘制pandas
groupby
对象。绘图(x=['time'],y=['battery'],ax=ax,title=str(I))

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

资料

完整代码

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()
当前绘图

稍微整理一下数据:

    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值转换为datetime,才能像往常一样正确绘制。您也可以在数据帧中这样做

结果,由imei标记:

(注意:编辑以消除我第一次遇到的一个奇怪问题。如果将列表作为
y
参数传递给
group.plot
,则列表ID将用作行标签,可能是在同时绘制多个因变量时的一个方便默认值

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

)

您能否发布一个用作groupby方法输入的示例数据帧?什么是
fil.imei
?如果只执行ax.legend(),会发生什么情况?如果使用稍微干净一点的语法,答案应该是非常清楚的。呵呵。
#for name, group in fil.groupby('imei'):
#    group.plot(x=['time'], y=['battery_raw'], ax=ax, label=name)