【问题标题】:how to add data labels on top of all bars in searborn barplot?如何在 seaborn barplot 中的所有条形顶部添加数据标签?
【发布时间】:2017-06-29 21:23:32
【问题描述】:

我的数据如下:

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

【问题讨论】:

    标签: python matplotlib data-visualization seaborn


    【解决方案1】:

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

    barwidth = [0.4, 0.4, 0.4, 0.4]
    

    正如你现在所拥有的,你的 for 循环只经历了两次迭代,因为它受到 barwidth 长度的限制。

    【讨论】:

    • 非常感谢! @迈克尔
    猜你喜欢
    • 2020-09-12
    • 2019-04-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多