图中图例中的 pandas groupby对象 [英] Pandas groupby object in legend on plot
问题描述
我正在尝试使用代码fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i))
问题在于,图例图例列出了['battery']
作为图例值.鉴于它正在为groupby
对象中的每个项目画一条线,因此将这些值绘制在图例中更为有意义.但是我不确定该怎么做.任何帮助将不胜感激.
The problem is the plot legend lists ['battery']
as the legend value. Given it's drawing a line for each item in the groupby
object, it makes more sense to plot those values in the legend instead. However I'm not sure how to do that. Any help would be appreciated.
数据
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()
当前图
推荐答案
稍微整理的数据:
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才能正确绘制.您也可以在数据框中执行此操作.
The x-values have to be converted to datetime for plotting to come out right, as usual. You could do that in the dataframe, too.
结果,以imei标记:
Result, labeled by imei:
(注意:已编辑,以消除我第一次遇到的奇怪情况.如果将列表作为y
参数传递给group.plot
,则列表ID将用作行标签,大概是方便的默认值一次绘制多个因变量时.
(NOTE: edited to get rid of an oddity I tripped over the first time. If you pass a list as the y
argument to group.plot
, the list IDs will be used as the line labels, presumably as a handy default for when you're plotting several dependent variables at once.
#for name, group in fil.groupby('imei'):
# group.plot(x=['time'], y=['battery_raw'], ax=ax, label=name)
)
这篇关于图中图例中的 pandas groupby对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!