循环生成子图时出现错误

18

我有一个问题,关于当我循环绘制数据框中的多个子图时收到的错误。

我的数据框有很多列,我循环遍历每一列以创建一个子图。

这是我的代码

 def plot(df):
    channels=[]
    for i in df:
        channels.append(i)

    fig, ax = plt.subplots(len(channels), sharex=True, figsize=(50,100))

    plot=0    
    for j in df: 

        ax[plot].plot(df["%s" % j])
        ax[plot].set_xlabel('%s' % j)
        plot=plot+1

    plt.tight_layout()
    plt.show() 

我成功地生成了情节,但同时也出现了空的框架和错误信息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\AClayton\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 538, in runfile
    execfile(filename, namespace)
  File "C:/Users/AClayton/Desktop/Data/TS.py", line 67, in <module>
    plot(all_data)
  File "C:/Users/AClayton/Desktop/Data/TS.py", line 49, in plot
    ax[plot].plot(reader["%s" % j])
TypeError: 'AxesSubplot' object does not support indexing

如果第一张图绘制正常,我不知道这个错误来自哪里,或者为什么会生成第二个图形?

感谢任何见解。

1个回答

65
如果你绘制多个子图,plt.subplots() 函数返回一个包含轴对象的数组。这个数组可以像使用 ax[plot] 一样索引。但是当只有一个子图时,默认情况下它会返回轴本身,而不是包含在数组中的轴。
因此,当 len(channels) 等于1 时,会出现错误。可以通过在 .subplots() 命令中设置 squeeze=False 来防止这种行为发生。这将强制它始终返回一个“行x列”大小的轴数组,即使只有一个子图。
因此,代码如下:
 def plot(df):
    channels=[]
    for i in df:
        channels.append(i)

    fig, ax = plt.subplots(len(channels),1, sharex=True, figsize=(50,100), squeeze=False)

    plot=0    
    for j in df: 

        ax[plot,0].plot(df["%s" % j])
        ax[plot,0].set_xlabel('%s' % j)
        plot=plot+1

    plt.tight_layout()
    plt.show() 
通过添加squeeze关键字,您始终会得到一个2D数组作为返回值,因此子图的索引方式更改为ax[plot,0]。我还特别添加了列数(在本例中为1)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接