【问题标题】:How to give a gap between bar chart and frame如何在条形图和框架之间给出间隙
【发布时间】:2020-03-11 14:18:37
【问题描述】:

我尝试在每个条形图的顶部制作带有标签的分组条形图,但标签总是穿过框架。我想让标签不越过框架,但标签仍然在栏的顶部。 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)

【问题讨论】:

    标签: python matplotlib charts bar-chart


    【解决方案1】:

    嗯,一种可能的方法是通过将上限从 100 更改为 115 来向上移动绘图的上边界:

    ax.set_ylim(bottom=0, top=115)
    

    如果您想确保保持相同的yticks,只需添加:

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


    完整代码如下:

    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=115)
        ax.set_yticks(np.arange(0, 105, 20))
    
    autolabel(rects1)
    autolabel(rects2)
    

    【讨论】: