将值标签添加到组条形图

时间:2018-08-15 18:06:40

标签: python pandas matplotlib bar-chart

我尝试按照此post向条形图添加标签,它可以编译,但标签完全错误。我不知道为什么.patches值如此不同。高度和标签不对应。这是数据框的代码段。

 prefix     suffix  fx  netwt   cmpdNames   replicates
0   141808060   11  fraction_1  0.20    Me-4-Hy     0
1   141808060   11  fraction_1  0.03    Me-4-Hy     1
2   141808060   11  fraction_1  -0.07   Et-4-Hy     0
3   141808060   11  fraction_1  0.17    Et-4-Hy     1
4   141808060   12  fraction_1  0.07    Uracil  0
5   141808060   12  fraction_1  30.50   Uracil  1
6   141808060   12  fraction_1  -0.02   BzPh    0
7   141808060   12  fraction_1  0.30    BzPh    1
8   141808060   21  fraction_2  -0.23   Me-4-Hy     0
9   141808060   21  fraction_2  -0.57   Me-4-Hy     1
10  141808060   21  fraction_2  -0.59   Et-4-Hy     0
11  141808060   21  fraction_2  -0.55   Et-4-Hy     1
12  141808060   22  fraction_2  -0.34   Uracil  0
13  141808060   22  fraction_2  7.59    Uracil  1
14  141808060   22  fraction_2  -0.41   BzPh    0
15  141808060   22  fraction_2  -0.41   BzPh    1

我认为可以使用pd.read_clipboard()将其复制为熊猫格式。

df = pd.read_clipboard()
fig,axs = plt.subplots(1,2,figsize=(16,8))
fig.subplots_adjust(hspace=0.5,wspace=0.2)
axs=axs.ravel() #returned contiguous flattened array
width=0.25
x = range(1,8)
ymin = min(df['netwt'])
ymax = max(df['netwt'])
fxname=['fx{}'.format(i+1) for i in range(7)]
cnames = ['Me-4-Hy', 'Et-4-Hy', 'Uracil', 'BzPh']
for i in range(4):
    y1 = df['netwt'][(df['cmpdNames']==cnames[i]) & (df['replicates']==0)].tolist()
    y2 = df['netwt'][(df['cmpdNames']==cnames[i]) & (df['replicates']==1)].tolist()
    x2 = [xs+0.25 for xs in x]
    axs[i].bar(x,y1,width,alpha=0.6,align='center')
    axs[i].bar(x2,y2,width,alpha=0.6,align='center')
    axs[i].set_title(cnames[i])
    axs[i].set_xticks([xd+0.1425 for xd in x])
    axs[i].set_xticklabels(fxname[i]) 
    axs[i].set_ylabel('mg')
    axs[i].set_ylim(ymin-1,ymax+4)
    patches1 = axs[i].patches[0:13:2] # evens
    patches2 = axs[i].patches[1:14:2] # odds

    for pa1,lbl1,pa2,lbl2 in zip(patches1,y1,patches2,y2):
        hgt1 = pa1.get_height()
        axs[i].text(pa1.get_x()+pa1.get_width()/2, hgt1+1,lbl1,ha='center',va='bottom',fontsize=11)
        hgt2 = pa2.get_height()
        axs[i].text(pa2.get_x()+pa2.get_width()/2, hgt2+1,lbl2,ha='center',va='bottom',fontsize=11)

这是我的输出: output

0 个答案:

没有答案