I am trying to loop over a groupby object and plot each group. But I am having some issues. Can someone please tell me where I am going wrong?
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);
It seems I'm close, but just there are some issues some where.
- First issue is that there are 5 groups in the groupby object. I get the 5 figures as I want, but only first one has the plots(lines) on it. Others figures are blank with the correct title on them, any idea what is wrong with my code?
- How can I set a group column / key as the x axis, I have tried this x=group.desiredx but it doesn't do anything.
mykey| year| val1| val2
item1| 2000| 5| 34
item2| 2001| 45| 34
item3| 2002| 34| 34
item1| 2000| 22| 65
item2| 2001| 34| 54
item3| 2002| 12| 54
item1| 2000| 23| 54
item2| 2001| 34| 34
item3| 2002| 21| 21