I am trying to combine three time-series plots from three different dataframes and plot them on the same figure.
I have tried various things but this is the baseline and my most intuitive method, however, I am not able to superimpose all three plots into one:
df_date_grouping = df['month_year'].value_counts().to_frame('Visits').rename_axis('dates').reset_index()
df_date_grouping = df_date_grouping.sort_values(by="dates")
df2_date_grouping = df2['month_year'].value_counts().to_frame('df2 Visits').rename_axis('dates').reset_index()
df2_date_grouping = df2_date_grouping.sort_values(by="dates")
df3_date_grouping = df3['month_year'].value_counts().to_frame('df3 Visits').rename_axis('dates').reset_index()
df3_date_grouping = df3_date_grouping.sort_values(by="dates")
df4_date_grouping = df4['month_year'].value_counts().to_frame('df4 Visits').rename_axis('dates').reset_index()
df4_date_grouping = df4_date_grouping.sort_values(by="dates")
plt.figure()
df_date_grouping.plot('dates', 'Visits' , color= 'purple')
df2_date_grouping.plot( 'dates', 'df2 Visits', color= 'blue')
df3_date_grouping.plot( 'dates', 'df3 Visits', color= 'orange' )
df4_date_grouping.plot( 'dates', 'df4 Visits', color= 'red')
plt.savefig(path)
plt.clf()
How can I keep all three in the same plot?
CodePudding user response:
Try this.
plt.figure()
fig,ax = plt.subplots()
df2_date_grouping.plot( 'dates', 'df2 Visits', color= 'blue',ax = ax)
df3_date_grouping.plot( 'dates', 'df3 Visits', color= 'orange',ax = ax)
df4_date_grouping.plot( 'dates', 'df4 Visits', color= 'red',ax = ax)
You need to plot them on the same axes. Pandas plotting is built on top of Matplotlib. You can use both matplotlib and pandas together. In this case, you expose the matplotlib axes to pandas plot and pandas will plot on the same axes.