简体   繁体   English

在 Seaborn 中用值标记水平条形图

[英]Labeling horizontal barplot with values in Seaborn

I have a horizontal barplot, for example, a simplified version of the example from the seaborn documentation :我有一个水平条形图,例如, seaborn 文档中示例的简化版本:

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 can I get the bars labeled with the value for each bar?如何获取标有每个条的值的条?

I tried this approach for vertical bars ( How to add percentages on top of bars in seaborn ), but it doesn't seem to work.我为垂直条尝试了这种方法( 如何在 seaborn 中的条形顶部添加百分比),但它似乎不起作用。 Changing height to width doesn't have the effect I assumed it would.将高度更改为宽度不会产生我认为的效果。

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

I'm assuming the horizontal plot works differently?我假设水平图的工作方式不同?

Got it, thanks to @ImportanceOfBeingErnest明白了,感谢@ImportanceOfBeingErnest

This worked for me这对我有用

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

As of matplotlib 3.4.0从 matplotlib 3.4.0 开始

Use the new built-in ax.bar_label , which will automatically label bar containers regardless of orientation:使用新的内置ax.bar_label ,无论方向如何,它都会自动标记 bar 容器:

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

If the bars are grouped by hue , call ax.bar_label on all the containers:如果条形图按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)

Thank you very much for this.非常感谢你。 It helped me a lot, but i ran to a problem, where percents had to many digits after decimal point, the format can be then simply specified:它对我帮助很大,但我遇到了一个问题,百分比必须在小数点后有很多位,然后可以简单地指定格式:

for container in ax.containers:
    ax.bar_label(container,size=8,fmt='%.1f')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM