简体   繁体   中英

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:

   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: 像这样 . How can I visualize my dataframe like the above figure using matplotlib.pyplot?

Use with DataFrame.pivot with DataFrame.plot.bar :

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

If need month names add rename after pivoting:

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. 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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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