增加成组的带注释的水平条形图的y间距以防止条形图重叠

时间:2020-11-08 19:27:50

标签: python matplotlib

如何在每个类别有3条的分组条形图之间增加间距,而又不会丢失条形图后面的正确注释?我已经尝试了一些方法,但无济于事。我为条形图准备的代码:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams.update(plt.rcParamsDefault)

labels = ["Top1", "Top3", "Top5", "Top10", "Top20", "Top50", "Top100", "Top200", "Top400"]
baseline=[21,23,23,25,25,30,33,33,33]
native_shape_3000_apo=[14,17,17,19,20,20,21,22,28]
conformer_shape_3000_holo=[11,15,17,19,23,29,32,34,36]

x = np.arange(len(baseline))
print(x)
width = 0.4
fig, axes = plt.subplots(1,2, figsize=(12,4), sharey= False, sharex=False)
axes= axes.flatten()
rects1=axes[0].barh(x - width, baseline, width, label='Baseline',color='black',edgecolor='black')
rects2=axes[0].barh(x + width, native_shape_3000_apo, width,label='x', color='yellow',edgecolor='black')
rects3=axes[0].barh(x, conformer_shape_3000_holo, width, label='y')

axes[0].set_xlim(xmin=0, xmax=47)
axes[0].set_xticks([x for x in range(0,48,10)])
axes[0].set_yticks(x)
axes[0].set_yticklabels(labels)
axes[0].legend(loc=4, prop={'size': 8})

def autolabel(rects, axes):

    for rect in rects:
        width = rect.get_width()
        perc=int(round(width/47*100))
        axes.annotate(f'{width} ({perc}%) ',
                      xy=(width, rect.get_y()+ rect.get_height()/2), 
                      xytext=(2,1),
                      textcoords="offset points",
                      ha='left', va='center_baseline',fontsize=6)
        
autolabel(rects1, axes[0])
autolabel(rects2, axes[0])
autolabel(rects3, axes[0])

plt.show()

enter image description here

1 个答案:

答案 0 :(得分:1)

当前x轴间距值为1,因此,如果将其扩展,该问题将消失。现在您需要调整宽度。下图的宽度已更正为0.5。

x = np.arange(0,len(baseline)*2, 2)
[ 0  2  4  6  8 10 12 14 16]

enter image description here