首页 > 解决方案 > how to combine two or more pandas dataframes with different length time-series for matplotlib plots?

问题描述

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?

标签: pythonpandasdataframematplotlibtime-series

解决方案


尝试这个。

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)

您需要将它们绘制在相同的轴上。Pandas 绘图建立在 Matplotlib 之上。您可以同时使用 matplotlib 和 pandas。在这种情况下,您将 matplotlib 轴暴露给 pandas 绘图,并且 pandas 将在相同的轴上绘图。


推荐阅读