简体   繁体   English

如何迭代 matplotlib 子图中的轴

[英]How to iterate axes in matplotlib subplots

I'm trying to add a title for 5x2 subplots using matplotlib and the code I wrote is as follows:我正在尝试使用 matplotlib 为 5x2 子图添加标题,我编写的代码如下:

fig, axs = plt.subplots(5, 2, figsize=(2*len(cols)+1, 2*len(rows)+1))
for i, ax in axs.flat:

    # print(sum_cols_level[i]) 
      ax.set_title(cols_level[i])

When I run this getting this error当我运行这个得到这个错误

TypeError: cannot unpack non-iterable AxesSubplot object类型错误:无法解包不可迭代的 AxesSubplot 对象

cols_level is a list containing list of numbers [1,2,3,4.. etc] cols_level 是一个包含数字列表的列表 [1,2,3,4.. 等]

I also tried我也试过

for i, ax in enumerate(axs.flat):

and got this error;并得到这个错误;

IndexError: index 9 is out of bounds for axis 0 with size 9索引错误:索引 9 超出轴 0 的范围,大小为 9

I really appreciate somebody can explain how ax is working and why I'm getting those errors!我真的很感激有人可以解释 ax 是如何工作的以及为什么我会收到这些错误!

The proper solution really depends on what cols_level is.正确的解决方案实际上取决于cols_level是什么。 Still, the problem seems to be that you are trying to unzip a 1D numpy flatiter as it was 2D.不过,问题似乎是您试图解压缩 1D numpy flatiter,因为它是 2D。 Forgot to use enumerate ?忘记使用enumerate

fig, axs = plt.subplots(2, 2, figsize=(6,8))
cols_level = [f'ax_{i}' for i in range(len(axs.flat))]
for i, ax in enumerate(axs.flat):
      ax.set_title(cols_level[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM