【问题标题】:For Loop over a function with a for loop insideFor 循环一个带有 for 循环的函数
【发布时间】: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


【解决方案1】:

由于没有数据,我从 Seabon 转移了样本数据。对函数的修改是使图形单元为外循环,柱状图为内循环,并使用枚举函数。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

tips = sns.load_dataset("tips")

p1 = tips.groupby('sex')['total_bill'].sum().to_frame()
p2 = tips.groupby('smoker')['total_bill'].sum().to_frame()
p3 = tips.groupby('day')['total_bill'].sum().to_frame()
p4 = tips.groupby('time')['total_bill'].sum().to_frame()

fig, ax = plt.subplots(1,4, sharey=True, figsize=[16,5])

opleiding_plot = ax[0].bar(p1.index, p1.total_bill)
geslacht_plot = ax[1].bar(p2.index, p2.total_bill)
coachervaring_plot = ax[2].bar(p3.index, p3.total_bill)
sport_plot = ax[3].bar(p4.index, p4.total_bill)

plot_list = [opleiding_plot,geslacht_plot,coachervaring_plot,sport_plot]

def autolabel(plots):
    for i,bars in enumerate(plots):
        for k,b in enumerate(bars):
            height = b.get_height()
            # print(height)
            ax[i].text(b.get_x() + b.get_width()/2., 1.02*height, '%d' % int(height), ha='center', va='bottom')

autolabel(plot_list)

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()

【讨论】:

  • 是的,这行得通,谢谢!过去,我曾经与 dput() for R 共享我的数据。对于 Python,有什么方法可以做到这一点? “对函数的修改是使图形单元为外循环,条形图为内循环,并使用枚举函数。”很好的解释,这有助于我理解它:) 我仍然觉得有时很难崩溃,在家上学:)
猜你喜欢
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 2021-10-28
  • 2017-08-28
相关资源
最近更新 更多