使用Seaborn中的值标记水平条形图 [英] Labeling horizontal barplot with values in Seaborn

查看:44
本文介绍了使用Seaborn中的值标记水平条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个水平条形图,例如,来自seaborn文档的示例的简化版本:https://seaborn.pydata.org/examples/horizo​​ntal_barplot.html

I have a horizontal barplot, for example, a simplified version of the example from the seaborn documentation: https://seaborn.pydata.org/examples/horizontal_barplot.html

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?

我对竖线尝试了这种方法(如何在seaborn的酒吧顶部添加百分比?),但这似乎不起作用.将高度更改为宽度不会产生我认为的效果.

I tried this approach for vertical bars ( How to add percentages on top of bars in seaborn?) , but it doesn't seem to work. 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?

推荐答案

明白了,感谢@ImportanceOfBeingErnest

Got it, thanks to @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

这篇关于使用Seaborn中的值标记水平条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆