来自 plt.subplots() 的轴是一个 "numpy.ndarray" 对象并且没有属性 "plot"

Axes from plt.subplots() is a "numpy.ndarray" object and has no attribute "plot"

The information below may be superfluous if you are trying to understand the error message. Please start off by reading by @user707650.

使用 MatPlotLib,我想要一个可通用的脚本,它可以根据我的数据创建以下内容。

A window 包含 a 个子图,排列成 b每列 个子图。我希望能够更改 ab[= 的值56=]。

如果我有 2a 子图的数据,我想要 2 个 windows,每个子图都有前面描述的“a 根据每列 b 个子图排列的子图".

我正在绘制的 x 和 y 数据是存储在 np.arrays 中的浮点数,其结构如下:

  • 所有绘图的 x 数据始终相同且长度为 5。

     'x_vector': [0.000, 0.005, 0.010, 0.020, 0.030, 0.040]
    
  • 所有地块的 y 数据存储在 y_vector 中,其中第一个地块的数据存储在索引 0 到 5 处。第二个地块的数据存储在索引 6 到 11 中。第三个地块的索引为 12-18,第四个地块的索引为 19-24,依此类推。

对于这个数据集,我总共有 91 个图(即 91*6 = 546 个值存储在 y_vector 中)。

尝试:

import matplotlib.pyplot as plt

# Options:
plots_tot = 14 # Total number of plots. In reality there is going to be 7*13 = 91 plots.
location_of_ydata = 6 # The values for the n:th plot can be found in the y_vector at index 'n*6' through 'n*6 + 6'.
plots_window = 7 # Total number of plots per window.
rows = 2 # Number of rows, i.e. number of subplots per column.

# Calculating number of columns:
prim_cols = plots_window / rows
extra_cols = 0
if plots_window % rows > 0:
    extra_cols = 1
cols = prim_cols + extra_cols

print 'cols:', cols
print 'rows:', rows

# Plotting:
n=0
x=0
fig, ax = plt.subplots(rows, cols)
while x <= plots_tot:
    ax[x].plot(x_vector, y_vector[n:(n+location_of_ydata)], 'ro')
    if x % plots_window == plots_window - 1:
        plt.show() # New window for every 7 plots.
    n = n+location_of_ydata
    x = x+1

我收到以下错误:

cols: 4
rows: 2
Traceback (most recent call last):
  File "Script.py", line 222, in <module>
    ax[x].plot(x_vector, y_vector[n:(n+location_of_ydata)], 'ro')
AttributeError: 'numpy.ndarray' object has no attribute 'plot'

如果您通过简单地打印 ax 来调试程序,您很快就会发现 ax 是一个二维数组:一维用于行,一维用于列。

因此,您需要两个索引来索引 ax 以检索实际的 AxesSubplot 实例,例如:

ax[1,1].plot(...)

如果您想按照现在的方式遍历子图,首先展平 ax

ax = ax.flatten()

现在 ax 是一个一维数组。我不知道是否先遍历行或列,但如果它是错误的,请使用转置:

ax = ax.T.flatten()

当然,现在简单地动态创建每个子图更有意义,因为它已经有一个索引,并且其他两个数字是固定的:

for x < plots_tot:
     ax = plt.subplot(nrows, ncols, x+1)

注意:您有 x <= plots_tot,但是 x 从 0 开始,您将在当前代码的下一个 IndexError(展平数组后)。 Matplotlib 是(不幸的)子图的 1 索引。我更喜欢使用 0 索引变量(Python 样式),只需为子图索引添加 +1(如上)。

如果您使用 N×1 图,例如如果您喜欢 fig, ax = plt.subplots(3, 1) 那么请点赞ax[plot_count].plot(...)

这里的问题在于 matplotlib 如何处理子图。只需执行以下操作:

fig, axes = plt.subplots(nrows=1, ncols=2)
for axis in axes:
    print(type(axis))

你将得到一个 matplotlib 对象,它实际上是一个一维数组,可以使用单个索引遍历,即轴 [0]、轴 [1]... 等等。但如果你这样做

fig, axes = plt.subplots(nrows=2, ncols=2)
for axis in axes:
    print(type(axis))

你会得到一个 numpy ndarray 对象,它实际上是一个二维数组,只能使用 2 个索引遍历,即 axis[0, 0]、axis[1, 0]...等等。因此,请注意如何合并 for 循环以遍历轴对象。

轴是二维的,而不是一维的,因此您不能使用一个循环进行迭代。你还需要一个循环:

 fig,axes=plt.subplots(nrows=2,ncols=2)
    plt.tight_layout()
    for ho in axes:
        for i in ho:
            i.plot(a,a**2)

这没有问题,但如果我尝试:

for i in axes:
      i.plot(a,a**2)

发生错误。