2017-02-11 16 views
0

我的數據是象下面這樣:如何將數據標籤添加到搜索barplot中所有酒吧的頂部?

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 barplot:

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

回答

0

你剛纔定義barwidth了一個小的失誤。它的長度應該有四個:

barwidth = [0.4, 0.4, 0.4, 0.4] 

正如你現在擁有它,你的循環只會通過兩次迭代,因爲它通過barwidth長度的限制。

+0

非常感謝! @邁克爾 – zesla