python - `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
,返回二维数组和迭代其元素的首选方法是nditer
(https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html)。那么为什么它在这种情况下不起作用并且我正在迭代的元素具有类型<class 'numpy.ndarray'>
而不是<class 'matplotlib.axes._subplots.AxesSubplot'>
?
解决方案
对数组进行迭代,nditer
可以将原始数组的单元格视为 0 维数组。对于非对象数组,这几乎等同于产生标量,因为 0 维数组通常表现得像标量,但这不适用于对象数组。
迭代一个对象数组flat
只是直接给你对象。
推荐阅读
- java - 在多个步骤定义类之间传递场景上下文
- java - Spring Boot 中的所有资源都需要这个可能的 set defual 角色吗?
- android - 超过 26 岁的 Android 文件提供程序问题
- angular - 在扩展面板中突出显示扩展面板的单选按钮
- c# - 带有身份服务器 4 的 URL 令牌
- angular - (ngModelChange) 不会更新特定输入的 UI
- paypal - 对我的 Paypal 交易已通过 API 验证,但我的账户余额为 0.00 美元
- php - 我在处理 PHP 中的大 CSV 文件时遇到问题
- python - 如何将变量存储在外部文件中
- vb.net - 随机化列表中的字符串