供以后参考,它有一个完整的工作示例,以便有人可以复制和粘贴您的代码并直接重现您的问题,以供参考.例如,我可以看到您已经导入了ImageGrid,但是完整的import语句将对此有所帮助,就像为data1a,data1b等创建假数据集一样.
此外,看起来您在上面的语句中应该有(1,6),而您应该在其中有(1,4):grid = ImageGrid(fig,111,(1,4),Aspect = False,share_all = False),尽管这不是解决您问题的方法.
当我想要两个或多个颜色条时,我的方法通常是在轴上使用get_position(),该方法将轴角的坐标作为属性x0,y0,x1,y1返回.从这里开始,我分别定义每个颜色条的轴,并将每个精确地放置在我希望它移动的位置.为了满足您的需求,您必须在下面的代码中修改fig.add_axes([1.01,bbox_ax.y0,0.02,bbox_ax.y1-bbox_ax.y0])的详细信息.例如,前两个条目1.01 bbox_ax.y0的意思是“将下角放在x = 1.01且y = bbox_ax.y0”.后两个条目0.02,bbox_ax.y1-bbox_ax.y0分别定义了颜色条轴的水平和垂直宽度.我希望颜色条轴与绘图轴齐平,因此我将bbox_ax.y1-bbox_ax.y0用作垂直宽度.
请注意,由于我不太熟悉后者,所以我使用的是mp.subplots()而不是ImageGrid(),并且我认为这不是必需的.
import matplotlib.pyplot as mp
import numpy
import mpl_toolkits.axes_grid1
data1a = numpy.random.rand(100,100)
data1b = numpy.random.rand(100,100)
data2a = numpy.random.rand(100,100)
data2b = numpy.random.rand(100,100)
fig, axes = mp.subplots(1, 4, figsize=(8,2))
im1a = axes[0].pcolormesh(data1a, cmap='magma')
im1b = axes[1].pcolormesh(data1b, cmap='magma')
im2a = axes[2].pcolormesh(data2a, cmap='viridis')
im2b = axes[3].pcolormesh(data2b, cmap='viridis')
fig.tight_layout()
# get bounding box information for the axes (since they're in a line, you only care about the top and bottom)
bbox_ax = axes[0].get_position()
# fig.add_axes() adds the colorbar axes
# they're bounded by [x0, y0, x_width, y_width]
cbar_im1a_ax = fig.add_axes([1.01, bbox_ax.y0, 0.02, bbox_ax.y1-bbox_ax.y0])
cbar_im1a = mp.colorbar(im1a, cax=cbar_im1a_ax)
cbar_im2a_ax = fig.add_axes([1.09, bbox_ax.y0, 0.02, bbox_ax.y1-bbox_ax.y0])
cbar_im1a = mp.colorbar(im2a, cax=cbar_im2a_ax)
这将产生下图:
您还可以将其作为2×2网格使用,语法略有不同:
fig, axes = mp.subplots(2, 2, figsize=(4,4))
im1a = axes[0,0].pcolormesh(data1a, cmap='magma')
im1b = axes[0,1].pcolormesh(data1b, cmap='magma')
im2a = axes[1,0].pcolormesh(data2a, cmap='viridis')
im2b = axes[1,1].pcolormesh(data2b, cmap='viridis')
fig.tight_layout()
bbox_ax_top = axes[0,1].get_position()
bbox_ax_bottom = axes[1,1].get_position()
cbar_im1a_ax = fig.add_axes([1.01, bbox_ax_top.y0, 0.02, bbox_ax_top.y1-bbox_ax_top.y0])
cbar_im1a = mp.colorbar(im1a, cax=cbar_im1a_ax)
cbar_im2a_ax = fig.add_axes([1.01, bbox_ax_bottom.y0, 0.02, bbox_ax_bottom.y1-bbox_ax_bottom.y0])
cbar_im1a = mp.colorbar(im2a, cax=cbar_im2a_ax)
产生此图: