【问题标题】:Value on top of a barplot in pythonpython中条形图顶部的值
【发布时间】:2017-03-25 07:59:36
【问题描述】:

我在 pandas df 中有一个表,其中有 avg_sp 和 count1 作为列。我绘制了一个按范围分组的条形图,还为顶部的值添加了一个 for 循环。

plt.figure(figsize=(12, 6))
df2 = df.groupby(pd.cut(df['avg_sp'], range(0, 110,10))).sum()  ['count1'].plot(kind='bar')
plt.xlabel('avg_sp')
plt.ylabel('browse count')

for p in df2.patches:
    df2.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005),rotation=90)

但是我没有得到正确的结果,如下图,它与x轴混合,有什么办法可以把数字调高一点吗?

我添加了 pirsquared 建议的代码,但它只影响顶部栏,其他保持不变。

【问题讨论】:

  • @lanery 我希望这些值垂直倾斜
  • 您可以将参数rotation=90添加到ax.annotate
  • @lanery 我补充说,检查我的新情节,没有。相互混合
  • @MaxU 你能帮帮我吗?

标签: python python-2.7 python-3.x pandas matplotlib


【解决方案1】:

考虑系列s

s = pd.Series(np.random.randn(10000))
s.hist()


from matplotlib docs

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

ax = s.hist()
for c in ax.containers:
    autolabel(c)


ax.patches 相同的解决方案

ax = s.hist()
for rect in ax.patches:
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
            '%d' % int(height),
            ha='center', va='bottom')


rotated labels docs

ax = s.hist()
for rect in ax.patches:
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
            '%d' % int(height),
            ha='center', va='bottom', rotation=90)


我稍微弄乱了高度设置以将其放置在我想要的位置

ax = s.hist()
for rect in ax.patches:
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., 1.01*height+100,
            '%d' % int(height),
            ha='center', va='bottom', rotation=90)

【讨论】:

  • 和 rotation = 90 也可以解决这个问题?顺便,谢谢
  • 在我的 barplot 中没有发生高度变化,它几乎触及 x 轴,即使在运行您编辑的帖子之后,只有第一个栏受到影响,剩余的栏距离是还是一样
  • 尝试运行完全相同的代码,看看它是否适用于我提供的示例。如果它不起作用,则意味着您的库版本或其他与系统相关的版本存在差异。如果它确实有效,则意味着您在某处有错字,或者您必须将高度调整到更极端的程度,例如添加 200 而不是 100。
  • 我用了200,300等组合,但只影响一个吧!而不是所有的酒吧,我在运行你的代码后添加了我的情节的另一个快照
  • 请注意,我在最后一个示例中添加了内容。当仅使用乘数缩放时,非常小的数字保持非常小。这就是为什么它看起来只适用于最右边的酒吧。因为这是最大的,也是对乘数反应最大的
猜你喜欢
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 2021-12-05
  • 2022-01-23
  • 1970-01-01
  • 2019-04-03
  • 2017-06-04
  • 2022-07-06
相关资源
最近更新 更多