感谢以上所有答案。但是,就像一些答案和 cmets 指出的那样,axes_grid1 模块无法解决 GeoAxes,而调整 fraction、pad、shrink 和其他类似参数不一定能给出非常精确的顺序,这真的很困扰我。我相信为colorbar 提供自己的axes 可能是解决上述所有问题的更好解决方案。
代码
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))
# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.
cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)
结果
后来,我发现matplotlib.pyplot.colorbar official documentation 也提供了ax 选项,它们是现有的轴,将为颜色条提供空间。因此,它对于多个子图很有用,见下文。
代码
fig, ax = plt.subplots(2,1,figsize=(12,8)) # Caution, figsize will also influence positions.
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
fig.colorbar(im1, ax=ax)
结果
同样,您也可以通过指定 cax 来实现类似的效果,从我的角度来看,这是一种更准确的方式。
代码
fig, ax = plt.subplots(2,1,figsize=(12,8))
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
cax = fig.add_axes([ax[1].get_position().x1-0.25,ax[1].get_position().y0,0.02,ax[0].get_position().y1-ax[1].get_position().y0])
fig.colorbar(im1, cax=cax)
结果