简体   繁体   中英

Plotting multiple lines in one chart but next to each other using matplotlib

I have the following quarterly df.

group date          share
A     2018-03-31    0.03
A     2018-06-30    0.03
A     2018-09-30    0.03
A     2018-12-31    0.02
A     2019-03-31    0.02
B     2018-03-31    0.04
B     2018-06-30    0.04
B     2018-09-30    0.05
B     2018-12-31    0.06
B     2019-03-31    0.07
C     2018-03-31    0.05
C     2018-06-30    0.06
C     2018-09-30    0.07
C     2018-12-31    0.07
C     2019-03-31    0.09

UPDATE

i used the code suggested below

fig,ax=plt.subplots(figsize=(10,6))
df.set_index(['group'], append=True).unstack()['share'].plot(ax=ax)
ax.set(xticks=np.arange(0,len(df)))
plt.legend(loc='upper left')
ax.set_xticklabels(df.date.dt.to_period('Y').astype(str).values, rotation = 45)
ax.grid(which='major', alpha=0.5)
ax.grid(which='minor', alpha=0.2)
plt.ylim(0, 0.22)
plt.show()

I have this overlapping x-axis ticks. How can i only have the start and the end year for each group?

在此处输入图像描述

As your dates are repeating but you do not want the lines on top of one another, you will need to plot the data as you have done above and then change the tick labels so that the dates show up. See if this is what you are looking for... Note that I have plotted with the limited data you have provided.

fig,ax=plt.subplots(figsize=(10,6))
df.set_index('group', append=True).unstack()['share'].plot(ax=ax)
ax.set(xticks=np.arange(0,len(df)))
ax.set_xticklabels(df.date.astype(str).values, rotation = 45)
ax.grid(None)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM