简体   繁体   English

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 the answer by @user707650 .请首先阅读@user707650的答案

Using MatPlotLib, I wanted a generalizable script that creates the following from my data.使用 MatPlotLib,我想要一个通用的脚本,从我的数据创建以下内容。

A window containing a subplots arranged so that there are b subplots per column.一个包含一个子图的窗口,排列成每列有b个子图。 I want to be able to change the values of a and b .我希望能够更改ab的值。

If I have data for 2a subplots, I want 2 windows, each with the previously described " a subplots arranged according to b subplots per column".如果我有2a个子图的数据,我想要 2 个窗口,每个窗口都有前面描述的“ a子图根据每列b个子图排列”。

The x and y data I am plotting are floats stored in np.arrays and are structured as follows:我绘制的 x 和 y 数据是存储在 np.arrays 中的浮点数,其结构如下:

  • The x data is always the same for all plots and is of length 5.所有图的 x 数据始终相同,长度为 5。

     'x_vector': [0.000, 0.005, 0.010, 0.020, 0.030, 0.040]
  • The y data of all plots are stored in y_vector where the data for the first plot is stored at indexes 0 through 5. The data for the second plot is stored at indexes 6 through 11. The third plot gets 12-18, the fourth 19-24, and so on.所有图的 y 数据都存储在y_vector 中,其中第一个图的数据存储在索引 0 到 5。第二个图的数据存储在索引 6 到 11。第三个图获得 12-18,第四个图获得 19 -24,以此类推。

In total, for this dataset, I have 91 plots (ie 91*6 = 546 values stored in y_vector).总的来说,对于这个数据集,我有 91 个图(即 91*6 = 546 个存储在 y_vector 中的值)。

Attempt:尝试:

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

I get the following error:我收到以下错误:

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'

If you debug your program by simply printing ax , you'll quickly find out that ax is a two-dimensional array: one dimension for the rows, one for the columns.如果您通过简单地打印ax调试您的程序,您会很快发现ax是一个二维数组:一维用于行,一维用于列。

Thus, you need two indices to index ax to retrieve the actual AxesSubplot instance, like:因此,您需要两个索引来索引ax以检索实际的AxesSubplot实例,例如:

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

If you want to iterate through the subplots in the way you do it now, by flattening ax first:如果您想以现在的方式遍历子图,请先将ax平:

ax = ax.flatten()

and now ax is a one dimensional array.现在ax是一个一维数组。 I don't know if rows or columns are stepped through first, but if it's the wrong around, use the transpose:我不知道是先遍历行还是列,但如果周围有问题,请使用转置:

ax = ax.T.flatten()

Of course, by now it makes more sense to simply create each subplot on the fly, because that already has an index, and the other two numbers are fixed:当然,现在简单地动态创建每个子图更有意义,因为它已经有一个索引,另外两个数字是固定的:

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

Note: you have x <= plots_tot , but with x starting at 0, you'll get an IndexError next with your current code (after flattening your array).注意:您有x <= plots_tot ,但是当x从 0 开始时,接下来您的当前代码会得到一个IndexError (在展平数组之后)。 Matplotlib is (unfortunately) 1-indexed for subplots. Matplotlib 是(不幸的是)子图的 1 索引。 I prefer using a 0-indexed variable (Python style), and just add +1 for the subplot index (like above).我更喜欢使用 0 索引变量(Python 样式),只需为子图索引添加+1 (如上所述)。

The problem here is with how matplotlib handles subplots.这里的问题在于 matplotlib 如何处理子图。 Just do the following:只需执行以下操作:

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

you will get a matplotlib object which is actually a 1D array which can be traversed using single index ie axis[0], axis[1]...and so on.你会得到一个 matplotlib 对象,它实际上是一个一维数组,可以使用单个索引遍历,即轴 [0]、轴 [1]...等等。 But if you do但是如果你这样做

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

you will get a numpy ndarray object which is actually a 2D array which can be traversed only using 2 indices ie axis[0, 0], axis[1, 0]...and so on.你会得到一个 numpy ndarray 对象,它实际上是一个二维数组,只能使用 2 个索引来遍历,即轴 [0, 0]、轴 [1, 0]...等等。 So be mindful how you incorporate your for loop to traverse through axes object.因此,请注意如何合并 for 循环以遍历轴对象。

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

The axes are in 2-d, not 1-d so you can't iterate through using one loop.轴是 2 维的,而不是 1 维的,因此您无法使用一个循环进行迭代。 You need one more loop:你还需要一个循环:

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

This gives no problem but if I try:这没有问题,但如果我尝试:

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

the error occurs.错误发生。

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

相关问题 来自 plt.subplots() 的 matplotlib 轴的精确类型注释数组(numpy.ndarray) - Precise type annotating array (numpy.ndarray) of matplotlib Axes from plt.subplots() 为什么在 for 循环中定义的子图表现不一致? (&#39;numpy.ndarray&#39; 对象没有属性 &#39;plot&#39;) - Why defined subplots within for-loop behave inconsistently? ('numpy.ndarray' object has no attribute 'plot') 使用轴进行子图获取 AttributeError 的问题:&#39;numpy.ndarray&#39; 对象没有属性 &#39;plot&#39; - Prob using axes for subplot an get AttributeError: 'numpy.ndarray' object has no attribute 'plot' AttributeError:“ numpy.ndarray”对象没有属性“ plot” - AttributeError: 'numpy.ndarray' object has no attribute 'plot' &#39;numpy.ndarray&#39; 对象没有属性 &#39;values&#39; - 'numpy.ndarray' object has no attribute 'values' &#39;numpy.ndarray&#39;对象没有属性&#39;mode&#39; - 'numpy.ndarray' object has no attribute 'mode' &#39;numpy.ndarray&#39; 对象没有属性 &#39;imshow&#39; - 'numpy.ndarray' object has no attribute 'imshow' &#39;numpy.ndarray&#39;对象没有属性&#39;count&#39; - 'numpy.ndarray' object has no attribute 'count' &#39;numpy.ndarray&#39; 对象没有属性 &#39;index&#39; - 'numpy.ndarray' object has no attribute 'index' &#39;numpy.ndarray&#39;对象没有属性&#39;insert&#39; - 'numpy.ndarray' object has no attribute 'insert'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM