我有一个水平条形图,例如,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/