【发布时间】:2021-03-23 02:59:07
【问题描述】:
所以我试图对子图执行 for 循环,以便分别正确标记每个子图中的条形。我知道我应该对“自动标签”功能进行循环,但我似乎无法让它工作。在示例中,这些值似乎在图中选择了正确的位置,但没有选择要显示的正确图。
这是我在准备数据后可视化的代码。
# 4. visualise
# plot style
plt.style.use('ggplot')
# create subplots
fig, ax = plt.subplots(1,4, sharey=True, figsize=[16,5])
# create bar containers for plots
opleiding_plot = ax[0].bar(opleidingsniveau.index, opleidingsniveau)
geslacht_plot = ax[1].bar(geslacht.index, geslacht)
coachervaring_plot = ax[2].bar(coachervaring.index, coachervaring['Coachervaring'])
sport_plot = ax[3].bar(sport.index, sport)
# create function to add frequency above all bars
plots = [0,1,2,3]
for i in plots:
def autolabel(bars):
# attach some text labels
for bar in bars:
height = bar.get_height()
ax[i].text(bar.get_x() + bar.get_width()/2., 1.02*height,
'%d' % int(height),
ha='center', va='bottom')
# use function over bar containers
autolabel(opleiding_plot)
autolabel(geslacht_plot)
autolabel(coachervaring_plot)
autolabel(sport_plot)
ax[0].title.set_text('Opleidingsniveau')
ax[0].set_xticklabels(['HBO', 'VO & MBO', 'WO en Post-WO'],rotation=20)
ax[1].title.set_text('Geslacht')
ax[2].title.set_text('Coachervaring in jaren')
ax[2].set_xticks([0,1,2,3])
ax[2].set_xticklabels(['0 t/m 6', '7 t/m 9', '10 t/m 16', '17 en hoger'], rotation=20)
ax[3].title.set_text('Sport')
plt.ylim([0,50])
plt.ylabel('Aantallen')
plt.show()
我也尝试过使用 for 循环在不同位置的绘图。
def autolabel(bars):
# attach some text labels
for bar in bars:
height = bar.get_height()
for i in plots:
ax[i].text(bar.get_x() + bar.get_width()/2., 1.02*height,
'%d' % int(height),
ha='center', va='bottom')
顺便说一句,我也试着写:
plots = [0]
for i in enumerate(plots):
def autolabel(bars):
# attach some text labels
for bar in bars:
height = bar.get_height()
ax[i].text(bar.get_x() + bar.get_width()/2., 1.02*height,
'%d' % int(height),
ha='center', va='bottom')
这给了我这个错误: IndexError: 数组索引过多
我对今天有点失去希望了哈哈。希望有人能帮我解决这个问题。
【问题讨论】:
-
我建议您退后一步,尝试正确标记第一把斧头,然后再尝试迭代其他斧头。
-
另外,在任何循环之外定义您的函数,并注意 enumerate() 从“plots”变量(这里相同)返回索引和值。
标签: python function for-loop matplotlib