如何在条形图和框架之间留出空隙

时间:2019-11-15 12:13:10

标签: python matplotlib charts bar-chart

我尝试制作条形图的组,每个条形图的顶部都带有标签,但是标签总是越过框架。我想使标签不越过框架,但标签仍位于栏的顶部。 my bar

def autolabel(rects):#label di atas bar
for rect in rects:
    height = rect.get_height()
    ax.annotate('{}'.format(height),
        xy=(rect.get_x() + rect.get_width() / 2, height),
        xytext=(0,3),  # 3 points vertical offset
        textcoords='offset points',
        ha='center',va='bottom')

plt.rcParams['figure.figsize'] = 6, 10. #w,h
labels = ['1', '2', '3', '4','5']
men_means = [20, 34, 30, 35, 98]
women_means = [25, 32, 86, 20, 25]
shemale_means = [45, 37, 95, 25, 22]

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig1, ax1 = plt.subplots(ncols=1, nrows=4, constrained_layout=True)

for ax in ax1.flat:
    rects1 = ax.bar(x - width/2, men_means, width, label='Testing Prediction')
    rects2 = ax.bar(x+ width/2, women_means, width, label='Training Prediction')

    ax.set_title('Title', fontsize=12)
    ax.set_ylabel('Scores')
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    ax.tick_params(axis="x", labelsize=8)
    ax.set_ylim(bottom=0, top=100)
autolabel(rects1)
autolabel(rects2)

1 个答案:

答案 0 :(得分:0)

好吧,一种可能的方法是通过将上限从let path = Bundle(for: type(of: self)).path(forResource: "TestingImage", ofType: "jpg") 更改为100来向上移动图的顶部边界:

115

如果您要确保保持相同的ax.set_ylim(bottom=0, top=115) ,只需添加:

yticks

Here's what i got


完整代码如下:

ax.set_yticks(np.arange(0, 105, 20))