首页 > 解决方案 > `nditer` 和 `flat` 之间的区别,元素的类型

问题描述

我创建了子图,我想xlim为每个子图进行修改。我编写了以下代码来做到这一点:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 3, figsize=(20, 10))

for ax in np.nditer(axs, flags=['refs_ok']):
    ax.set_xlim(left=0.0, right=0.5)

但我收到以下错误:

AttributeError: 'numpy.ndarray' object has no attribute 'set_xlim'

我做了更多的研究,最终使用它flat来实现我想要的。但我不明白为什么nditer没有按预期工作。为了说明这一点 - 以下代码:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 3, figsize=(20, 10))

print("Using flat")
for ax in axs.flat:
    print(ax, type(ax))

print("Using nditer")
for ax in np.nditer(axs, flags=['refs_ok']):
    print(ax, type(ax))

给出了这个结果:

Using flat
AxesSubplot(0.125,0.536818;0.227941x0.343182) <class 'matplotlib.axes._subplots.AxesSubplot'>
AxesSubplot(0.398529,0.536818;0.227941x0.343182) <class 'matplotlib.axes._subplots.AxesSubplot'>
AxesSubplot(0.672059,0.536818;0.227941x0.343182) <class 'matplotlib.axes._subplots.AxesSubplot'>
AxesSubplot(0.125,0.125;0.227941x0.343182) <class 'matplotlib.axes._subplots.AxesSubplot'>
AxesSubplot(0.398529,0.125;0.227941x0.343182) <class 'matplotlib.axes._subplots.AxesSubplot'>
AxesSubplot(0.672059,0.125;0.227941x0.343182) <class 'matplotlib.axes._subplots.AxesSubplot'>

Using nditer
AxesSubplot(0.125,0.536818;0.227941x0.343182) <class 'numpy.ndarray'>
AxesSubplot(0.398529,0.536818;0.227941x0.343182) <class 'numpy.ndarray'>
AxesSubplot(0.672059,0.536818;0.227941x0.343182) <class 'numpy.ndarray'>
AxesSubplot(0.125,0.125;0.227941x0.343182) <class 'numpy.ndarray'>
AxesSubplot(0.398529,0.125;0.227941x0.343182) <class 'numpy.ndarray'>
AxesSubplot(0.672059,0.125;0.227941x0.343182) <class 'numpy.ndarray'>

据我了解plt.subplots,返回二维数组和迭代其元素的首选方法是nditerhttps://docs.scipy.org/doc/numpy/reference/arrays.nditer.html)。那么为什么它在这种情况下不起作用并且我正在迭代的元素具有类型<class 'numpy.ndarray'>而不是<class 'matplotlib.axes._subplots.AxesSubplot'>

标签: pythonpython-3.xnumpymatplotlib

解决方案


对数组进行迭代,nditer可以将原始数组的单元格视为 0 维数组。对于非对象数组,这几乎等同于产生标量,因为 0 维数组通常表现得像标量,但这不适用于对象数组。

迭代一个对象数组flat只是直接给你对象。


推荐阅读