【发布时间】: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需要前两个参数为x和y,即ax.text(x,y)。您正在为它提供ax.text(y,x)。我还建议不要将width标记为"height",因为这会混淆包括您自己在内的所有人。
标签: python matplotlib seaborn bar-chart