在此数据集上绘制条形图时遇到麻烦。
+------+------------+--------+
| 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()
我希望显示类似此图的
具有相同的传说
答案 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')
答案 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()
答案 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()