matplotlib 通过单个列表迭代子图轴数组

2024-02-15

是否有一种简单/干净的方法来迭代子图返回的轴数组,例如

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 or ncol == 1.

我尝试过列表理解,例如:

[element for tupl in tupleOfTuples for element in tupl]

但如果nrows or ncols == 1


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

重塑文档 http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html。 论据-1导致 reshape 来推断输出的尺寸。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

matplotlib 通过单个列表迭代子图轴数组 的相关文章

随机推荐