2

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

tryingtobeastoic
  • 175
  • 1
  • 14

2 Answers2

1

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()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

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:

enter image description here

Maryam
  • 660
  • 6
  • 19