如何在python中为子块运行智能循环

2024-09-28 21:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试图创建一个包含9个图形的3x3框,虽然我已经通过手动为每个单独的框编写代码来实现,但我想学习如何使用循环来实现它。我好像想不出来。目前,我正在使用以下工具:

from matplotlib import gridspec

f, ((ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9)) = plt.subplots(3, 3, sharex='col', sharey='row')

gs = gridspec.GridSpec(3, 3)
fig = plt.figure(figsize=(20,20))

fig.text(0.5, .95, 'Constant Slope for [O/Fe]/[Fe/H] for Various R and Z', ha='center', va='center', size = 50)
fig.text(0.5, 0.08, '[Fe/H]', ha='center', va='center', size = 60)
fig.text(0.09, 0.5, '[O/Fe]', ha='center', va='center', rotation='vertical', size = 60)

ax1 = plt.subplot(gs[0])
histogram1 = ax1.hist2d(fehsc, ofesc, bins=nbins, range=[[-1,.5],[0.2,0.4]])
counts = histogram1[0]
xpos = histogram1[1]
ypos = histogram1[2]
image = histogram1[3]
newcounts = counts #we're going to iterate over this

for i in range (nbins):
    xin = xpos[i]
    yin = ypos
    yline = m*xin + b
    reset = np.where(yin < yline) #anything less than yline we want to be 0
    #index = index[0:len(index)-1]  
    countout = counts[i]
    countout[reset] = 0
    newcounts[i] = countout
ax1.plot(xarr2, yarr2, color='w', linewidth='5', alpha = 0.3)
ax1.plot(xarr, yarr, color='r')
ax1.set_title('R in [5,7] kpc | Z in [1,2] kpc', size = 20)

ax2 = plt.subplot(gs[1])
histogram2 = ax2.hist2d(fehsc2, ofesc2, bins=nbins, range=[[-1,.5],[0.2,0.4]])
counts = histogram2[0]
xpos = histogram2[1]
ypos = histogram2[2]
image = histogram2[3]
newcounts = counts #we're going to iterate over this

for i in range (nbins):
    xin = xpos[i]
    yin = ypos
    yline = m*xin + b
    reset = np.where(yin < yline) #anything less than yline we want to be 0
    #index = index[0:len(index)-1]  
    countout = counts[i]
    countout[reset] = 0
    newcounts[i] = countout
ax2.plot(xarr2, yarr2, color='w', linewidth='5', alpha = 0.3)
ax2.plot(xarr, yarr, color='r')
ax2.set_title('R in [7,9] kpc | Z in [1,2] kpc', size = 20)

以此类推,直到ax9。

我试着做的是:

for k in range(1,10):
    ax[k] = plt.subplot(gs[0])
    histogram1 = ax[k].hist2d(fehsc, ofesc, bins=nbins, range=[[-1,.5],[0.2,0.4]])
    counts = histogram1[0]
    xpos = histogram1[1]
    ypos = histogram1[2]
    image = histogram1[3]
    newcounts = counts #we're going to iterate over this

    for i in range (nbins):
        xin = xpos[i]
        yin = ypos
        yline = m*xin + b
        reset = np.where(yin < yline) #anything less than yline we want to be 0
        countout = counts[i]
        countout[reset] = 0
        newcounts[i] = countout
    ax[k].plot(xarr2, yarr2, color='w', linewidth='5', alpha = 0.3)
    ax[k].plot(xarr, yarr, color='r')
    ax[k].set_title('R in [5,7] kpc | Z in [1,2] kpc', size = 20)

因为我想把ax(k)放在一个循环中,同时运行所有9个迭代。但显然这不是办法,或者根本不起作用。调用axú时,是否可以将它从1循环到9循环?


Tags: inforsizerangeaxcentercountsax1