通过for循环的Python变量名

通过for循环的Python变量名,python,matplotlib,Python,Matplotlib,在Matplotlib中,我使用以下命令设置轴标签: axes1.set_ylabel(“..”) 如果我有三个轴,有没有办法使用循环来执行以下操作 for i in range(3): axes[i].set_ylabel('AVG') 当然,这不是正确的语法,因为我没有使用列表/字典。但是,有人有什么建议吗?将您的轴列在列表中: my_axes = [] for n in range(1, 4): my_axes.append(fig.add_subplot(1, 3, n

在Matplotlib中,我使用以下命令设置轴标签: axes1.set_ylabel(“..”)

如果我有三个轴,有没有办法使用循环来执行以下操作

for i in range(3):
    axes[i].set_ylabel('AVG')

当然,这不是正确的语法,因为我没有使用列表/字典。但是,有人有什么建议吗?

将您的轴列在列表中:

my_axes = []
for n in range(1, 4):
    my_axes.append(fig.add_subplot(1, 3, n))
for ax in my_axes:
     ax.set_ylabel('AVG')

以下是我对多个仅垂直轴的用法:

f, axes = plt.subplots(nrows=3, ncols=1, figsize=(12,5))
try:
    iter(axes)       # Check if axes can be iterated over
except TypeError:
    axes = [axes]    # If not, then make it into a list

for ax in axes:
    ax.plot(x, y)
    ax.set_ylabel('AVG')

通常我甚至会根据我有多少行来改变数字大小。如果您有
ncols>1
,那么这样做会变得有点复杂。因此,这仅适用于垂直绘图。

将轴放入列表中,然后使用代码即可。现在,您建议我如何配置与每个轴对应的子图?例如axes1=fig.add_子批(1,3,1)axes2=fig.add_子批(1,3,2)axes3=fig.add_子批(1,3,3)您所说的配置是什么意思?只需访问它们
ax[0]
?所以通常我会执行以下操作:axes1=fig.add_子批(1,3,1)无论如何,是否可以使用for循环并生成轴列表[n]=fig.add_子图(…)我真的建议
pyplot.subplot(nrows,ncols)