繁体   English   中英

plt.subplots() 中的轴是“numpy.ndarray”对象,没有属性“plot”

[英]Axes from plt.subplots() is a “numpy.ndarray” object and has no attribute “plot”

如果您试图了解错误消息,以下信息可能是多余的。 请首先阅读@user707650的答案

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

一个包含一个子图的窗口,排列成每列有b个子图。 我希望能够更改ab的值。

如果我有2a个子图的数据,我想要 2 个窗口,每个窗口都有前面描述的“ 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 (如上所述)。

这里的问题在于 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 个索引来遍历,即轴 [0, 0]、轴 [1, 0]...等等。 因此,请注意如何合并 for 循环以遍历轴对象。

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

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

 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)

错误发生。

暂无
暂无

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

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