python - 使用 Seaborn 中的值标记水平条形图

标签 python matplotlib seaborn

我有一个水平条形图,例如,seaborn 文档中示例的简化版本: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 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")

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

最佳答案

明白了,感谢@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

关于python - 使用 Seaborn 中的值标记水平条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49820549/

相关文章:

Python 将立体声 .flac 转换为单声道

python - Matplotlib 曲面图显示不同值的相同颜色

python - 如何在子图之间创建空间?

python - Python 中数组的 2D 和 3D 散点直方图

python - 曲线和对角线之间的填充区域

python - 如何在seaborn的猫图中添加网格线?

Python套接字循环不会中断

python - 如何使用 PyGame 计时器事件?如何使用计时器将时钟添加到 pygame 屏幕?

Java Python 集成

python - matplotlib 中用于 SciPy 树状图的更大调色板 (Python)