繁体   English   中英

如何使用 matplotlib.pyplot 在 x 轴上创建分组条形图(按月和年)并在 y 轴上创建值?

[英]How to create a grouped bar chart (by month and year) on the x-axis and values on the y-axis using matplotlib.pyplot?

这是我的 dataframe:

   Year  Month    Views
0  2016      5    97162
1  2016      6   415627
2  2016      7   675071
3  2016      8   962525
4  2016      9  1244306

我希望将视图绘制在 y 轴上,而在 x 轴上我希望月份和年份如下所示: 像这样 . 如何使用 matplotlib.pyplot 可视化我的 dataframe,如上图所示?

DataFrame.pivotDataFrame.plot.bar一起使用:

df.pivot('Year','Month','Views').plot.bar()

如果需要月份名称,请在旋转后添加rename

month_dict = {1 : "January", 2 : "February", 3 : "March", 4 : "April", 
              5 : "May" , 6 : "June", 7 : "July", 8 : "August", 
              9 : "September", 10 : "October" ,11 : "November",12 : "December"}

df.pivot('Year','Month','Views').rename(columns=month_dict).plot.bar()

您可以简单地使用seaborn代替。 在大多数情况下,它的着色效果更好,而且更易于使用。

例如:

import pandas as pd
import seaborn as sns

df = pd.DataFrame({"year": [1,1,1,1,2,3,2,3,2,3],
                   "month": [4, 6, 7, 5, 4, 6, 7, 1, 1, 4],
                   "value": list(range(5,15))})


sns.barplot(data=df, y='value', x='year', hue='month')

output如下:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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