【问题标题】:Create 3x3 matplotlib subplot but with plots missing at certain locations创建 3x3 matplotlib 子图,但在某些位置缺少图
【发布时间】:2021-06-15 12:25:10
【问题描述】:

假设我想以通常的方式(plt.subplots 等)将 6 个图安排到子图设置中。

但出于可视化原因,我需要按以下方式排列它们:

|1 0 0 |

|1 1 0 |

|1 1 1 | 

其中 1 表示我想要一个情节,0 表示我不想要。我不完全确定如何使用 matplotlib 中的子图做到这一点。任何建议都会很棒 - 谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    使用Figure.add_gridspec 和Figure.add_subplot

    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure(constrained_layout=True)
    >>> gs = fig.add_gridspec(3, 3)
    >>> axes = [fig.add_subplot(gs[x,y])
                    for x in range(3) for y in range(3) if x >= y]
    >>> plt.show()
    

    【讨论】:

      【解决方案2】:

      您可以在要留空的地方填写空白子图,如下所示:

      import matplotlib.pyplot as plt
      import numpy as np
      
      
      x = np.linspace(0, 2 * np.pi, 400)
      y = np.sin(x ** 2)
      
      fig, ((ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9)) = plt.subplots(3, 3)
      fig.suptitle('Sharing x per column, y per row')
      ax1.plot(x, y)
      ax2.axis("off")
      ax3.axis("off")
      ax4.plot(x, -y, 'tab:green')
      ax5.plot(x, -y**2, 'tab:red')
      ax6.axis("off")
      ax7.plot(x, -y, 'tab:green')
      ax8.plot(x, -y**2, 'tab:red')
      ax9.plot(x, -y**2, 'tab:red')
      

      Example

      【讨论】:

        【解决方案3】:

        您可以创建 3x3 子图并使某些轴不可见:

        fig, axs = plt.subplots(3,3)
        fig.tight_layout(pad=2.0)
        axs[0,1].axis('off')
        axs[0,2].axis('off')
        axs[1,2].axis('off')
        

        输出:

        【讨论】:

          猜你喜欢
          • 2020-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-04
          • 2020-12-11
          • 2017-08-26
          • 1970-01-01
          相关资源
          最近更新 更多