Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I plot a Bar graph when comparing the rows? [duplicate]

I am having trouble in plotting a bar graph on this Dataset.

+------+------------+--------+
| Year | Discipline | Takers |
+------+------------+--------+
| 2010 | BSCS       |   213  |
| 2010 | BSIS       |   612  |
| 2010 | BSIT       |   796  |
| 2011 | BSCS       |   567  |
| 2011 | BSIS       |   768  |
| 2011 | BSIT       |   504  |
| 2012 | BSCS       |   549  |
| 2012 | BSIS       |   595  |
| 2012 | BSIT       |   586  |
+------+------------+--------+

I'm trying to plot a bar chart with 3 bars representing the number of takers for each year. This is the algorithm I did.

import matplotlib.pyplot as plt
import pandas as pd

Y = df_group['Takers']
Z = df_group['Year']

df = pd.DataFrame(df_group['Takers'], index = df_group['Discipline'])
df.plot.bar(figsize=(20,10)).legend(["2010", "2011","2012"])

plt.show()

I'm expecting to show something like this graph

With the same legends

enter image description here

like image 330
Benz Avatar asked Dec 17 '22 16:12

Benz


1 Answers

First reshape by DataFrame.pivot, plot and last add labels by this:

ax = df.pivot('Discipline', 'Year','Takers').plot.bar(figsize=(10,10))

for p in ax.patches: 
    ax.annotate(np.round(p.get_height(),decimals=2), (p.get_x()+p.get_width()/2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

pic

like image 58
jezrael Avatar answered Mar 07 '23 20:03

jezrael