我的数据如下:

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=",")


我试图制作一个带有每个条上方的数据标签的海洋条形图:

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个,每组一个。我无法找出解决问题的方法。非常感谢您的帮助。提前致谢。

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

最佳答案

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

barwidth = [0.4, 0.4, 0.4, 0.4]


就像您现在拥有的那样,您的for循环仅经历两次迭代,因为它受barwidth长度的限制。

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

10-13 05:28