Python 为什么我不在for循环中递增?

Python 为什么我不在for循环中递增?,python,numpy,for-loop,matplotlib,subplot,Python,Numpy,For Loop,Matplotlib,Subplot,我是编程新手,我想知道为什么我的I在for循环中没有递增。我想更新每个子地块的地块名称。谢谢。 您不需要使用当前_轴[i],只需当前_轴 此外,您可以用以下内容替换for循环: for i, current_ax in enumerate(axes, 0): current_ax.set_title(f'Plot: {i}') 这是因为您的轴阵列如下所示 [[<matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA

我是编程新手,我想知道为什么我的
I
在for循环中没有递增。我想更新每个子地块的地块名称。谢谢。


您不需要使用
当前_轴[i]
,只需
当前_轴

此外,您可以用以下内容替换for循环:

for i, current_ax in enumerate(axes, 0):
    current_ax.set_title(f'Plot: {i}')

这是因为您的轴阵列如下所示

[[<matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA32BB2E0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA54476A0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x000001DCA547D250>]]
输出图

终端输出

figarray1 [[<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEB72B2E0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF9266A0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF95D250>]]
figarray2 [<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEB72B2E0>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF9266A0>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF95D250>]
1
2
3
figarray1[[
]]
Figaray2[
]
1.
2.
3.

我建议在这里使用
枚举
,因为它被认为比索引更具python风格

下面是如何设置标题: 输出:

。当前的\u ax已经是一个Axes实例。您不需要再次使用
i
索引它,因为这就是您循环的原因。所以:
current\u ax.set\u title()
应该是sufficient@LordVoldemortP,请考虑投票和/或接受一些答案,如果你发现它们有用的话;相反,请随便说说他们为什么不这样做。这个解释太棒了。非常感谢@伏地魔大人,这是正确的答案,我建议你批准它(点击答案正文左侧的复选标记)-我想补充一点,你的问题来自于关键词参数
squeak=False
,如果你在没有
squeak=False
的情况下尝试你的代码,那么你编写的循环是完全正确的。在
子窗口(…)
中播放不同数量的行和列,无论是否使用
挤压=False
,您都会明白我的意思…
from matplotlib import pyplot as plt
fig= plt.figure()
fig,axes = plt.subplots(nrows=1, ncols=3,squeeze=False)
fig.tight_layout()
i=0
print('figarray1',axes)
axes=axes[0]
print('figarray2',axes)
for current_ax in axes:
    current_ax.set_title(f"plot: {i}")
    i+=1
    print(i)
plt.show()
figarray1 [[<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEB72B2E0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF9266A0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF95D250>]]
figarray2 [<matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEB72B2E0>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF9266A0>
 <matplotlib.axes._subplots.AxesSubplot object at 0x0000020AEF95D250>]
1
2
3
import matplotlib.pyplot as plt

fig = plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=3, squeeze=False)
fig.tight_layout()

# enumerate titles for each plot (blue boxes in output below)   
for i, ax in enumerate(axes.flat):
    ax.set_title(f'Title {i}')

# label x and y axis for each plot (red boxes in output below)
plt.setp(axes, xlabel='x axis label')
plt.setp(axes, ylabel='y axis label')