【问题标题】:How to change spacing between only 1 pair of subplots in matplotlib如何更改 matplotlib 中仅一对子图之间的间距
【发布时间】:2022-01-05 15:03:40
【问题描述】:

我有一个带有多个子图的图形,我使用 gridspec 设置了这些子图:

        fig = Figure(figsize)
        gs = gridspec.GridSpec(4, 3, height_ratios=(1, 1,1,0.1))
        # Make axes on the subplots
        self.ax_main = self.fig.add_subplot(gs[1:3, :2]) 
        self.ax_x = self.fig.add_subplot(gs[0, :2],sharex=self.ax_main) 
        self.ax_y = self.fig.add_subplot(gs[1:3, 2],sharey=self.ax_main) 
        self.ax_cb = self.fig.add_subplot(gs[3, :2])

现在我想将 ax_cb 和 ax_main 之间的间距调整为一些手动设置的值。这可能吗?如果可以,怎么做?

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    将其称为 ax_cb 听起来像是您希望它成为一个颜色条。我不建议通过像这样的额外 gridspec 列添加颜色条。而是:

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib as mpl
    
    fig, axs = plt.subplot_mosaic([['x', '.'],  # '.' is empty
                                   ['main', 'y']],
                                  gridspec_kw={'height_ratios':[1, 2],
                                               'width_ratios':[2, 1]},
                                  constrained_layout=True)
    
    pc = axs['main'].pcolormesh(np.random.randn(20, 20))
    fig.colorbar(pc, ax=axs['main'], location='bottom', pad=0.25)
    plt.show()
    

    pad 参数以父轴为单位,在本例中为高度,您可以控制它与其他轴的距离。但是,如果您使用 constrained_layout,您可能会发现没有必要使用 pad。

    您可以使用 gridspec 做同样的事情,就像您在上面所做的那样,但 subplot_mosaic 通常更容易,而且人们似乎还不知道它。

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多