python - 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?
解决方案
尝试这个。
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 将在相同的轴上绘图。
推荐阅读
- python - 如何在不添加参数的情况下对基于时间的函数进行单元测试
- c++ - Cuda 从黑白图像创建纹理对象
- javascript - Service Worker 和 GCM 有什么区别
- python - sqlite3.OperationalError: near "t": syntax error 是什么意思
- reactjs - Redux 在按钮单击后没有很快更新-Redux,Reactjs
- jestjs - 笑话:其中没有 .test 或 .spec 的文件名
- java - Spring - 如何将组件从另一个模块注入到 SpringBoot 应用程序中
- c# - C#慢递归方法
- matlab - 双积分 - Matlab
- javascript - Javascript解决不做预期的事情