Skip to main content
 首页 » 编程设计

python之Matplotlib 子图解包不开心

2025年05月04日14Renyi-Fan

我正在使用 Jupyter notebook,我想要一个子图网格,它是 6 个图高 x 4 个图深。

在添加任何数据或操作绘图之前,我尝试单独运行以下行:

f, (ax1, ax2) = plt.subplots(6, 4, sharex=True, figsize=(13, 7)) 

它给出了这个异常(exception):

--------------------------------------------------------------------------- ValueError                                Traceback (most recent call last) <ipython-input-66-4b47dbb065be> in <module>() 
     12 # fig, ax = plt.subplots(1, 1, figsize=(13, 7)) 
     13  
---> 14 f, (ax1, ax2) = plt.subplots(6, 4, sharex=True, figsize=(13, 7)) 
     15 # ax1.plot(x, y) 
     16 # ax1.set_title('Sharing Y axis') 
 
ValueError: too many values to unpack 

请您参考如下方法:

您正在尝试创建一个 6x4 (=24) 子图的网格,但您只命名了 2 个子图以捕获从 plt.subplots 返回的内容,因此它试图解包 24 个子图分为两个变量(ax1 和 ax2)。

你有几个选择:

  1. 在一个容器中捕获所有子图实例,然后对其进行索引以访问各个子图:

    f, axes = plt.subplots(6, 4, sharex=True, figsize=(13, 7)) 
    axes[0,0].plot(x,y)  # plot on top left subplot 
    axes[2,1].plot(x,y)  # plot on subplot in column 3, row 2 
    
  2. 单独捕获所有子图:

    fig, ( 
          (ax11, ax21, ax31, ax41), 
          (ax12, ax22, ax32, ax42), 
          (ax13, ax23, ax33, ax43), 
          (ax14, ax24, ax34, ax44), 
          (ax15, ax25, ax35, ax45), 
          (ax16, ax26, ax36, ax46) 
         ) = plt.subplots(6, 4, sharex=True, figsize=(13, 7)) 
    ax11.plot(x,y)  # plot on top left axes 
    ax32.plot(x,y)  # plot on subplot in column 3, row 2