gpt4 book ai didi

python - 如何在seaborn barplot中的所有条形顶部添加数据标签?

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:34 25 4
gpt4 key购买 nike

我的数据如下:

data=io.StringIO("""x1,x2,x3
1,A,0.42
1,B,0.62
2,A,0.24
2,B,0.58
""")
df = pd.read_csv(data, sep=",")

我试图制作一个seaborn条形图,每个条形上方都有数据标签:

ax = sns.barplot (data=df, x='x2', y='x3', hue='x1', 
palette=sns.xkcd_palette(['blue', 'red']))
ax.legend(loc='center right', bbox_to_anchor=(1.03, 0.9),
ncol=1, fancybox=True, shadow=True)

barwidth = [0.4,0.4]
ax.set_ylim(0, 0.7)
label_ = df.x3
for bar,newwidth, label in zip(ax.patches,barwidth, label_):
x = bar.get_x()
width = bar.get_width()
height = bar.get_height()

centre = x+width/2.
bar.set_x(centre-newwidth/2.)
bar.set_width(newwidth)

ax.text(x+width/2.,
height + 0.03,
'{0:4.2f}'.format(label),
ha="center")

但是,这就是我得到的。 Seaborn 似乎将这些条视为两个补丁而不是 4 个,每组一个。我想不出解决问题的方法。非常感谢您的帮助。提前致谢。

enter image description here

最佳答案

您刚刚在定义barwidth时犯了一个小错误。它的长度应该是四:

barwidth = [0.4, 0.4, 0.4, 0.4]

正如您现在所看到的,您的 for 循环仅经历两次迭代,因为它受到 barwidth 长度的限制。

关于python - 如何在seaborn barplot中的所有条形顶部添加数据标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42177844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com