问题描述
该ax
返回值是一个numpy的阵列,其可以,我相信,重新成形而不的数据的任何复制。如果使用以下内容,则会得到一个线性数组,可以对其进行干净的迭代。
nrow = 1; ncol = 2;
fig, axs = plt.subplots(nrows=nrow, ncols=ncol)
for ax in axs.reshape(-1):
ax.set_ylabel(str(i))
当ncols和nrows均为1时,这并不成立,因为返回值不是数组;您可以将返回值转换为具有一个元素的数组以保持一致性,尽管感觉有点像笨拙:
nrow = 1; ncol = 1;
fig, axs = plt.subplots(nrows=nrow, ncols=nrow)
axs = np.array(axs)
for ax in axs.reshape(-1):
ax.set_ylabel(str(i))
解决方法
是否有一种简单/干净的方法来迭代子图等返回的轴数组
nrow = ncol = 2
a = []
fig,axs = plt.subplots(nrows=nrow,ncols=ncol)
for i,row in enumerate(axs):
for j,ax in enumerate(row):
a.append(ax)
for i,ax in enumerate(a):
ax.set_ylabel(str(i))
甚至适用于nrow
或ncol == 1
。
我尝试了列表理解,例如:
[element for tupl in tupleOfTuples for element in tupl]
但是如果nrows
或ncols == 1