matplotlib 中的子图给出 ValueError:没有足够的值来解包

use*_*322 7 python matplotlib

下面的代码给出了一个错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-ea5c06641335> in <module>()
     14 values = usa.loc[: , "GDP Billions"]
     15 
---> 16 fig, (ax1, ax2, ax3, ax4) = plt.subplots(2, 2, figsize=(15, 6))
     17 
     18 fig.suptitle('GDP Growth', fontsize=20)

ValueError: not enough values to unpack (expected 4, got 2)
Run Code Online (Sandbox Code Playgroud)

如果我将 fig, 更改(ax1, ax2, ax3, ax4) = plt.subplots(2, 2, figsize=(15, 6))fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))并删除相应的代码ax3ax4下面的代码,它会按需要工作。不知道为什么它不能按书面方式工作。

    %matplotlib inline
    import matplotlib.pyplot as plt
    import matplotlib.ticker
    import numpy as np
    from numpy import array

    plt.style.use('seaborn-white')

    plt.rc('ytick', labelsize=14) 
    plt.rc('xtick', labelsize=14) 

    # Plot GDP/Year
    names =  usa.loc[: , "Year"]
    values = usa.loc[: , "GDP Billions"]

    fig, (ax1, ax2, ax3, ax4) = plt.subplots(2, 2, figsize=(15, 6))

    fig.suptitle('GDP Growth', fontsize=20)

    ax1.plot(names, values)
    ax1.xaxis.set_ticks(np.arange(0, 57, 8))
    ax1.set_ylabel('GDP', fontsize=16)
    ax1.set_title('United States',fontsize=16)
    ax1.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

    ax2.plot(names, values)
    ax2.xaxis.set_ticks(np.arange(0, 57, 8))
    ax2.set_ylabel('Year', fontsize=16)
    ax2.set_title('China',fontsize=16)
    ax2.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

    ax3.plot(names, values)
    ax3.xaxis.set_ticks(np.arange(0, 57, 8))
    ax3.set_ylabel('GDP', fontsize=16)
    ax3.set_title('United States',fontsize=16)
    ax3.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

    ax4.plot(names, values)
    ax4.xaxis.set_ticks(np.arange(0, 57, 8))
    ax4.set_ylabel('Year', fontsize=16)
    ax4.set_title('China',fontsize=16)
    ax4.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

    plt.show()
Run Code Online (Sandbox Code Playgroud)

Dan*_*enz 12

plt.subplots() 将为您提供一个二维轴数组(在您的情况下为 2x2),因此您需要按如下方式进行设置:

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(
                                    ncols=2,
                                    nrows=2,
                                    figsize=(15, 6))
Run Code Online (Sandbox Code Playgroud)

或者,您也可以使用:

fig, axes = plt.subplots(
                     ncols=2,
                     nrows=2,
                     figsize=(15, 6))

ax1, ax2, ax3, ax4 = axes.flatten()
Run Code Online (Sandbox Code Playgroud)