【发布时间】:2018-05-13 19:16:32
【问题描述】:
我正在尝试遍历 groupby 对象并绘制每个组。但我有一些问题。谁能告诉我哪里出错了?
df = pd.DataFrame([['item1',2000,1, 2], ['item1',2001,1, 2], ['item1',2002,1, 2],
['item2',2000,1, 2], ['item2',2001,1, 2], ['item2',2002,1, 2]],
columns=['mykey', 'year','val1','val2'])
grouped = df.groupby('mykey')
for name,group in grouped:
fig = plt.figure()
ax1 = fig.add_subplot(111)
group.val1.plot.line(ax=ax1, ylim=[5,20], color='red',x=group.year)
ax1.set_ylabel('val1')
ax2 = ax1.twinx()
group.val2.plot.line(ax=ax2, ylim=[5,20], color='blue' ,x=group.year)
ax2.set_ylabel('val2')
plt.title(str(name), fontsize=15);
看来我已经接近了,但只是在某些地方存在一些问题。
- 第一个问题是 groupby 对象中有 5 个组。我得到了我想要的 5 个数字,但只有第一个有图(线)。其他数字是空白的,上面有正确的标题,知道我的代码有什么问题吗?
- 如何将组列/键设置为 x 轴,我试过这个 x=group.desiredx 但它没有做任何事情。
我的钥匙|年份| val1| val2
项目1| 2000| 5| 34
项目2| 2001| 45| 34
项目3| 2002| 34| 34
项目1| 2000| 22| 65
项目2| 2001| 34| 54
项目3| 2002| 12| 54
项目1| 2000| 23| 54
项目2| 2001| 34| 34
项目3| 2002| 21| 21
【问题讨论】:
-
请阅读并理解minimal reproducible example。 How to make good reproducible pandas examples 上的问题可能会帮助您制作一个这样的例子。
-
谢谢布拉德,我已经添加了一些数据。这是 groupby 之前数据框的样子。
-
desiredx 来自哪里?
-
抱歉,desiredx 是年份。当我发布它时,我正在使代码通用。
标签: pandas matplotlib plot group-by