matplotlib通过单个列表迭代子图轴数组 [英] matplotlib iterate subplot axis array through single list

查看:98
本文介绍了matplotlib通过单个列表迭代子图轴数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单/干净的方法来迭代由

Is there a simple/clean way to iterate an array of axis returned by subplots like

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

甚至适用于nrowncol == 1.

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

I tried list comprehension like:

[element for tupl in tupleOfTuples for element in tupl]

,但是如果nrowsncols == 1

推荐答案

ax返回值是一个numpy数组,我相信可以在不复制任何数据的情况下对其进行重塑.如果使用以下内容,则会得到一个线性数组,可以对其进行干净的迭代.

The ax return value is a numpy array, which can be reshaped, I believe, without any copying of the data. If you use the following, you'll get a linear array that you can iterate over cleanly.

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时,此方法不成立,因为返回值不是数组.您可以将返回值转换为具有一个元素的数组以保持一致性,尽管感觉有点像笨拙:

This doesn't hold when ncols and nrows are both 1, since the return value is not an array; you could turn the return value into an array with one element for consistency, though it feels a bit like a cludge:

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

重塑文档. 参数-1导致调整形状以推断输出的尺寸.

reshape docs. The argument -1 causes reshape to infer dimensions of the output.

这篇关于matplotlib通过单个列表迭代子图轴数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆