循环生成子图时出错

Ash*_*ton 18 python matplotlib dataframe subplot

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

我的数据框有很多列,我在其中循环以获得每列的子图.

这是我的代码

 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() 
Run Code Online (Sandbox Code Playgroud)

我得到的情节很好,但也是一个空框架和错误:

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
Run Code Online (Sandbox Code Playgroud)

如果第一个图表生成正常,或者为什么产生第二个图形,我看不出这个错误来自哪里?

感谢您的任何见解

Rut*_*ies 61

如果绘制多个子图,则plt.subplots()返回数组中的轴,该数组允许像您一样进行索引ax[plot].当只创建1个子图时,默认情况下它返回轴本身,而不是数组中的轴.

因此,当len(channels)等于1 时会发生错误.您可以通过squeeze=False.subplots()命令中进行设置来抑制此行为.这迫使它总是返回一个带有轴的'Rows x Cols'大小的数组,即使它只是一个.

所以:

 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() 
Run Code Online (Sandbox Code Playgroud)

通过添加squeeze关键字,您总是得到一个2D数组作为回报,因此子图的索引更改为ax[plot,0].我还特意添加了列数(在这种情况下为1).