使用 axes_grid1 而不操纵子图

Using axes_grid1 without manipulating subplots

我想使用 axes_grid1 在我的一个子图旁边绘制一个颜色条。 问题是,make_axes_locatable 的调用操纵了我的子图,因此它不再具有与其他图相同的大小。

这是我的问题的一个最小工作示例。

from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(15,5))
_ax = ax[0,:].flatten('C')
values_x = np.linspace(0, 2 * np.pi, 100)
values_y = np.sin(values_x)
vmax = np.amax(values_x)
vmin = np.amin(values_x)
s = 1
ticks_rotation = 10
ticks_num = 5
_ax = ax[0,:].flatten('C')
plot_w = _ax[0].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s)
plot_v = _ax[1].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s)
_ax = ax[1,:].flatten('C')
plot_w = _ax[0].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s)
plot_v = _ax[1].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s)

divider = make_axes_locatable(_ax[1])
cax = divider.append_axes('right', size='5%', pad=0.05)
v_delta = (vmax - vmin)*0.1
ticks = np.linspace(vmin+v_delta,vmax-v_delta,ticks_num)
cbar = fig.colorbar(plot_v, cax=cax, orientation='vertical', ticks=ticks)
cbar.ax.set_yticklabels(np.around(ticks,decimals=1), rotation=ticks_rotation,rotation_mode='default')
plt.show()

我想要的实际上是所有相同大小的子图,旁边有一个漂亮的颜色。 有什么建议吗?

编辑: 我真的只想在右下角的子图旁边有颜色条,而不是像 this.

如果你不执着于使用axes_grid1,我个人更喜欢使用a GridSpec来完成这种工作。

gridspec is a module which specifies the location of the subplot in the figure.

GridSpec

specifies the geometry of the grid that a subplot will be placed. The number of rows and number of columns of the grid need to be set. Optionally, the subplot layout parameters (e.g., left, right, etc.) can be tuned.

import matplotlib.gridspec as gs

gs0 = gs.GridSpec(2, 3, width_ratios=[20,20,1])
fig = plt.figure(figsize=(10,4))
ax1 = fig.add_subplot(gs0[0,0])
ax2 = fig.add_subplot(gs0[0,1])
ax3 = fig.add_subplot(gs0[1,0])
ax4 = fig.add_subplot(gs0[1,1])
cax = fig.add_subplot(gs0[:,2])


values_x = np.linspace(0, 2 * np.pi, 100)
values_y = np.sin(values_x)

for ax in [ax1,ax2,ax3,ax4]:
    plot_w = ax.scatter(values_x, values_y, c=values_x, cmap='rainbow', s=1)

cbar = fig.colorbar(plot_w, cax=cax, orientation='vertical')