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

霸气de小男生 提交于 2020-01-21 12:22:09

问题


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


回答1:


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')




回答2:


With Seaborn, you can directly use your Dataframe:

import seaborn as sns
ax = sns.barplot(data=df, x="Discipline", hue="Year", y="Takers")

To add the labels, you can use the snippet from jezrael:

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')
plt.tight_layout()




回答3:


Just add 2 more lines before plt.show() in your code and you will get your result. The whole code is given below.

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"])

for i,v in enumerate(Y):
    plt.text(x=i, y=v+2, s=v)
    # Here i= index value  
    # v= real value which you have in variable Y.
    # x and y are coordinate.
    # 's' is the value you want to show on the plot.

plt.show()


来源:https://stackoverflow.com/questions/56702605/how-do-i-plot-a-bar-graph-when-comparing-the-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!