[英]How to create a grouped bar chart (by month and year) on the x-axis and values on the y-axis using matplotlib.pyplot?
This is my dataframe:这是我的 dataframe:
Year Month Views
0 2016 5 97162
1 2016 6 415627
2 2016 7 675071
3 2016 8 962525
4 2016 9 1244306
I want the views to be plotted on the y-axis, and on the x-axis I want the months and years like this:我希望将视图绘制在 y 轴上,而在 x 轴上我希望月份和年份如下所示: . . How can I visualize my dataframe like the above figure using matplotlib.pyplot?如何使用 matplotlib.pyplot 可视化我的 dataframe,如上图所示?
Use with DataFrame.pivot
with DataFrame.plot.bar
:与DataFrame.pivot
和DataFrame.plot.bar
一起使用:
df.pivot('Year','Month','Views').plot.bar()
If need month names add rename
after pivoting:如果需要月份名称,请在旋转后添加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()
You can simply use seaborn
instead.您可以简单地使用seaborn
代替。 It's nicer in coloring, and easier to use, most of the times.在大多数情况下,它的着色效果更好,而且更易于使用。
For example:例如:
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')
The output is as follows: output如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.