比较行时如何绘制条形图?

时间:2019-06-21 11:31:47

标签: python python-3.x pandas matplotlib jupyter-notebook

在此数据集上绘制条形图时遇到麻烦。

+------+------------+--------+
| 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  |
+------+------------+--------+

我正在尝试绘制一个条形图,该条形图用3条形表示每年的接受者数量。这是我做的算法。

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

我希望显示类似此图的

具有相同的传说

enter image description here

3 个答案:

答案 0 :(得分:4)

首先通过DataFrame.pivot重塑形状,通过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

答案 1 :(得分:3)

通过Seaborn,您可以直接使用数据框:

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

要添加标签,您可以使用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()

grouped barplot

答案 2 :(得分:0)

只需在代码中的plt.show()之前再添加2行,您就会得到结果。 整个代码如下。

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