【问题标题】:Labeling horizontal barplot with values in Seaborn在 Seaborn 中用值标记水平条形图
【发布时间】:2018-09-24 00:33:28
【问题描述】:

我有一个水平条形图,例如example from the seaborn documentation的简化版:

import seaborn as sns
import matplotlib.pyplot as plt

f, ax = plt.subplots(figsize=(6, 15))

crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False)

sns.barplot(x="total", y="abbrev", data=crashes,
            label="Total", color="b")

ax.set(xlim=(0, 24), ylabel="",
       xlabel="Automobile collisions per billion miles")

plt.show()

如何获取标有每个条形值的条形?

我为竖线尝试了这种方法 (How to add percentages on top of bars in seaborn),但它似乎不起作用。将高度更改为宽度不会产生我认为的效果。

for p in ax.patches:
    height = p.get_width()
    ax.text(p.get_y()+p.get_height()/2.,
            height + 3,
            '{:1.2f}'.format(height),
            ha="center")

我假设水平图的工作方式不同?

【问题讨论】:

  • text 需要前两个参数为xy,即ax.text(x,y)。您正在为它提供ax.text(y,x)。我还建议不要将width 标记为"height",因为这会混淆包括您自己在内的所有人。

标签: python matplotlib seaborn bar-chart


【解决方案1】:

从 matplotlib 3.4.0 开始

使用新的内置ax.bar_label,无论方向如何,都会自动标记条形容器:

fig, ax = plt.subplots(figsize=(6, 8))
sns.barplot(x="total", y="abbrev", data=crashes)

# new helper method to auto-label bars
ax.bar_label(ax.containers[0])

如果条形图按hue 分组,请在所有容器上调用ax.bar_label

fig, ax = plt.subplots(figsize=(5, 6))
ax = sns.barplot(x="tip", y="day", hue="smoker", data=tips)

# grouped bars will have multiple containers
for container in ax.containers:
    ax.bar_label(container)

【讨论】:

    【解决方案2】:

    知道了,感谢@ImportanceOfBeingErnest

    这对我有用

    for p in ax.patches:
        width = p.get_width()    # get bar length
        ax.text(width + 1,       # set the text at 1 unit right of the bar
                p.get_y() + p.get_height() / 2, # get Y coordinate + X coordinate / 2
                '{:1.2f}'.format(width), # set variable to display, 2 decimals
                ha = 'left',   # horizontal alignment
                va = 'center')  # vertical alignment
    

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多