Python 如何在searborn barplot中的所有条顶部添加数据标签?

Python 如何在searborn barplot中的所有条顶部添加数据标签?,python,matplotlib,data-visualization,seaborn,Python,Matplotlib,Data Visualization,Seaborn,我的数据如下: 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.xkc

我的数据如下:

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将酒吧视为两块而不是四块,每组一块。我想不出解决这个问题的办法。非常感谢您的帮助。提前谢谢


您刚刚在定义
条码宽度时犯了一个小错误。其长度应为四:

barwidth = [0.4, 0.4, 0.4, 0.4]

现在,for循环只需要经过两次迭代,因为它受到barwidth长度的限制。

非常感谢@迈克尔