我正在尝试使用代码groupby
fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i))
对象
问题是情节图例列出了['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()
当前情节
答案 0 :(得分:10)
略微整理的数据:
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)
)