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



,如果您想了解错误消息,以下信息可能会多余。请从阅读答案开始 @user707650

使用matplotlib,我想要一个可推广的脚本,从我的数据中创建以下内容。

包含 a 子图的窗口已排列,以便每个列有 b 子图。我希望能够更改 a b 的值。

如果我有 2a 子图的数据,我想要2个窗口,每个窗口都带有上述" a 根据 B 子图的子图。

我绘制的X和Y数据是存储在NP的浮点,结构如下:

  • 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对象,该对象实际上是一个1D数组,可以使用单个索引(即轴[0],轴[1] ...等等。但是,如果您这样做

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

您将获得一个Numpy ndarray对象,该对象实际上是一个2D数组,只能使用2个索引即可遍历,即轴[0,0],轴[1,0] ...等等。因此,请注意如何将循环整合到轴对象中。

如果您使用n by 1图,例如,如果您喜欢fig, ax = plt.subplots(3, 1),请喜欢ax[plot_count].plot(...)

轴为2-D,而不是1-D,因此您不能使用一个循环迭代。您需要再循环:

 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)

发生错误。

相关内容

最新更新