【问题标题】:Annotating bar chart in pandas [duplicate]在 pandas 中注释条形图
【发布时间】:2018-05-16 04:39:38
【问题描述】:

我有一个条形图,其中显示 2 个条形图,一个代表 2015 年,一个代表 2016 年。

  • x轴显示药物名称
  • y 轴显示规定的数量

我想在条上显示注释只是为了更清楚地说明规定的数字。我尝试了以下但没有任何反应?

有人知道我哪里出错了吗?

这是我的代码

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

【问题讨论】:

  • 你需要在for后面的那一行输入4个空格。

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


【解决方案1】:

你认为这有帮助吗:

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

编辑

如果你想要更好的风格,你可以在开头添加这个

from matplotlib import pyplot as plt
plt.style.use('fivethirtyeight')

并将ax.legend(["2015", "2016"]) 修改为ax.legend(["2015", "2016"], frameon=False)。样式类型的完整列表plt.style.available

【讨论】:

    【解决方案2】:

    尝试将前两行移到plt.show() 之前。当前代码在定义之前引用了ax

    【讨论】:

      猜你喜欢
      • 2016-03-10
      • 2014-10-16
      • 2019-12-23
      • 2017-01-23
      相关资源
      最近更新 更多