gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:07:51 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

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

Here's what i got

<小时/>

完整代码如下:

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)

关于python - 如何在条形图和框架之间留出间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58876845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com