【问题标题】:Spacing between some subplots but not all一些子图之间的间距,但不是全部
【发布时间】:2015-07-17 20:33:56
【问题描述】:

我在 python 中有一个 matplotlib 图,有 3 个子图,都在 1 列中。

我目前控制每个子图的高度:

gridspec.GridSpec(3, 1, height_ratios=[1, 3, 3])

我没有空格通过:

plt.subplots_adjust(hspace=0.0)

但我只想在第 2 行和第 3 行之间留一些间距。

在其他答案之一中,我读到我可以执行以下操作:

gs1.update(left=0.05, right=0.48, wspace=0)

但我真的不明白发生了什么。有人可以给我更多信息吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    当您调用更新时,您会将这些参数应用于该特定网格规范中的所有子图。如果要对不同的子图使用不同的参数,可以制作多个网格规范。但是,您需要确保它们的大小正确且不重叠。一种方法是使用嵌套的网格规范。由于底部两个图的总高度是顶部的 6 倍,因此外部 gridspec 的高度比将为 [1, 6]。

    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    
    
    def do_stuff(cell): #just so the plots show up
        ax = plt.subplot(cell)
        ax.plot()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    plt.subplots_adjust(hspace=0.0)
    #make outer gridspec
    outer = gridspec.GridSpec(2, 1, height_ratios = [1, 6]) 
    #make nested gridspecs
    gs1 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec = outer[0])
    gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec = outer[1], hspace = .05)
    for cell in gs1:
        do_stuff(cell)
    for cell in gs2:
        do_stuff(cell)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      在这种特殊情况下,在第 2 行和第 3 行之间添加一个不可见的轴对象可能是最快的:

      import matplotlib.pyplot as plt
      
      gridspec = dict(hspace=0.0, height_ratios=[1, 1, 0.4, 3])
      fig, axs = plt.subplots(nrows=4, ncols=1, gridspec_kw=gridspec)
      axs[2].set_visible(False)
      

      我查看了文档,似乎不支持可变网格间距。因此,我们必须使用像这样的解决方法。

      【讨论】:

        【解决方案3】:

        您可以使用 gridspec 并定义一个没有内容的额外子图,并根据您希望在其他子图之间存在的空间给它一个小的宽度比。

        spec = gridspec.GridSpec(ncols=4, nrows=1, figure=fig,width_ratios=[1,1,0.4,2])
        ax00  = fig.add_subplot(spec[0, 0])
        ax01  = fig.add_subplot(spec[0, 1])
        ax03  = fig.add_subplot(spec[0, 3])
        

        在我的示例中,02 子图仅用于宽度比为 0.4 的间距:)。

        【讨论】:

          猜你喜欢
          • 2015-05-11
          • 2020-01-04
          • 1970-01-01
          • 1970-01-01
          • 2012-06-22
          • 1970-01-01
          • 2021-11-27
          • 1970-01-01
          • 2014-07-02
          相关资源
          最近更新 更多