【问题标题】:Matplotlib indexing error on plotting绘图时的 Matplotlib 索引错误
【发布时间】:2017-09-01 04:38:23
【问题描述】:

我基本上有以下脚本。但它在运行过程中失败,并在axarr[0].plot(x,y) 行出现以下错误TypeError: 'Figure' object does not support indexing 。我试图四处搜索,但在创建子图时发现了类似的错误......而且我只添加/替换数据(我不确定,因为它是一个 matlab 文件的副本,而我没有 matlab)。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 2, 0.01)
for idx in range(1, 10):
    a = 1 + (idx - 1) / 10

    y = a ** x

    axarr, fig = plt.subplots(1,1)
    axarr[0].plot(x,y)
    axarr.axis([0, 4, 0, 85])
    axarr[0].grid(True)
    plt.show()

我可能会收到此错误,因为我在循环中使用了一个图形,但它看起来在迭代 1 中失败了。那么我做错了什么或者有什么可以更好地使它起作用(几乎等于 matlab 文件,请参见下面的部分脚本)?
希望有人能帮忙。

matlab文件等号样例是这样的:

x = 0:0.01:4;
for idx = 1:10 
a = 1 + (idx-1)/10;

y = a.^x;
z = 2 * y
subplot(111)
plot(x,y)
hold on
plot(x(1:400),z)
axis([0 4 0 85])
pause
hold off

end

【问题讨论】:

  • 您的图形和坐标轴方向错误——应该是fix,axarr = plt.subplots(1,1)(您可以跳过1,1 部分。

标签: python-3.x matplotlib indexing


【解决方案1】:

这里有两个问题:

  1. plt.subplots 的返回是一个 (Figure, array of Axes) 的元组。因此,作业必须是

    fig, axarr = plt.subplots(1,1)
    
  2. 以上内容并不能完全解决问题,因为您最终会遇到类似的错误 (TypeError: 'AxesSubplot' object does not support indexing)。这是因为默认情况下plt.subplotsarray of Axes 减少到单个轴,以防仅使用一列和一行。 此行为由 squeeze 参数控制。因此,使用plt.subplots 的有效方法是

    fig, axarr = plt.subplots(1,1)
    axarr.plot(x,y)
    

    fig, axarr  = plt.subplots(1,1, squeeze=False)
    axarr[0,0].plot(x,y)
    

    请注意,您不需要 1,1 作为参数,因为它们是默认值。

【讨论】:

  • 因此,如果子图是(n,1),其中n 可能等于1,并且您想要遍历不同的事物以绘制所有索引将变为axarr[j, 0]
  • squeeze=False 有很大的不同!
猜你喜欢
  • 2019-04-01
  • 1970-01-01
  • 2019-10-11
  • 2017-07-22
  • 2017-04-23
  • 2011-12-09
  • 2021-11-27
相关资源
最近更新 更多