简体   繁体   中英

How to change spacing between only 1 pair of subplots in matplotlib

I have a figure with multiple subplots which I set up using 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])

and now I would like to adjust the spacing between ax_cb and ax_main to some manually set value. Is this possible? and if so, how could it be done?

Calling it ax_cb makes it sound like you want this to be a colorbar. I would not recommend adding colorbars via an extra gridspec column like this. Rather:

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()

The pad argument is in units of the parent axes, in this case it's height and lets you control its distance from the other axes. However if you use constrained_layout, you may find using the pad is not necessary.

在此处输入图像描述

You can do the same thing with gridspec, as you have done above, but subplot_mosaic is often easier, and people don't seem to know about it yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM