注释条形图在 pandas [英] Annotating bar chart in pandas
问题描述
我有一个条形图,其中显示2个条形,一个为2015年,另一个为2016年.
I have a bar chart that displays 2 bars one for 2015 and one for 2016.
- x轴显示药品名称
- y轴显示处方金额
我想在条形图上显示注释,只是为了使其更清楚地指定数字.我尝试了以下方法,但没有任何反应?
I would like to display annotation on the bars just to make it more clear the number prescribed. I have tried the following but nothing happens?
有人知道我要去哪里吗?
Does anyone know where I am going wrong?
这是我的代码
for p in ax.patches:
ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
fig = plt.figure() # Create matplotlib figure
ax = fig.add_subplot(111) # Create matplotlib axes
width = 0.4
df.Occurance_x.plot(kind='bar', color='purple', ax=ax, width=width, position=1)
df.Occurance_y.plot(kind='bar', color='blue', ax=ax, width=width, position=0)
ax.set_ylabel('Amount Prescribed in 1 year')
x_labels = df.VTM_NM
ax.set_xticklabels(x_labels, rotation=30)
plt.legend(['2016', '2017'], loc='upper right')
ax.set_title('BNF Chapter 1 Top 5 drugs prescribed')
plt.show()
推荐答案
您认为这可以帮助您吗:
Do you think that this can help:
import pandas as pd
df = pd.DataFrame({"date_x":[2015]*5,
"Occurance_x":[2994, 2543, 2307, 1535, 1511],
"VTM_NM":["Not Specified", "Mesalazine", "Omeprazole",
"Esomeprazole", "Lansoprazole"],
"date_y":[2016]*5,
"Occurance_y":[3212, 2397, 2370, 1516, 1547]})
ax = df[["VTM_NM","Occurance_x", "Occurance_y"]].plot(x='VTM_NM',
kind='bar',
color=["g","b"],
rot=45)
ax.legend(["2015", "2016"]);
for patch in ax.patches:
bl = patch.get_xy()
x = 0.5 * patch.get_width() + bl[0]
# change 0.92 to move the text up and down
y = 0.92 * patch.get_height() + bl[1]
ax.text(x,y,"%d" %(patch.get_height()),
ha='center', rotation='vertical', weight = 'bold')
修改
如果您想要更好的样式,可以在开头添加它
If you then want a nicer style you can add this at the beginning
from matplotlib import pyplot as plt
plt.style.use('fivethirtyeight')
并使用 ax.legend(["2015","2016"],frameon = False)修改
ax.legend(["2015","2016"])
代码>.有关样式的完整列表,请输入 plt.style.available
and modify ax.legend(["2015", "2016"])
with ax.legend(["2015", "2016"], frameon=False)
. For a full list of style type plt.style.available
这篇关于注释条形图在 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!