I use the following code to generate side-by-size images and I need to add colorbar only to the second image in the row. I use the following code for it

import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1 import make_axes_locatable

import matplotlib.gridspec as gridspec

def plotting(x):

gs1 = gridspec.GridSpec(1, 2)

gs1.update(wspace=0.005, hspace=0.005)

plt.subplot(gs1[0])

plt.imshow(x)

plt.axis('off')

plt.title('dog')

ax1 = plt.subplot(gs1[1])

imc = plt.imshow(x, cmap='hot', interpolation='nearest')

plt.axis('off')

plt.title('dog')

divider = make_axes_locatable(ax1)

cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(imc, cax=cax)

plt.tight_layout()

plt.show()

However it comes out the size of side-by-side images are not equal. I wonder how I could fix this issue?PmPyv.png

解决方案

You can use ImageGrid, which was created exactly for this purpose:

from mpl_toolkits.axes_grid1 import ImageGrid

x = np.random.random(size=(10,10))

fig = plt.figure()

grid = ImageGrid(fig, 111,

nrows_ncols = (1,2),

axes_pad = 0.05,

cbar_location = "right",

cbar_mode="single",

cbar_size="5%",

cbar_pad=0.05

)

grid[0].imshow(x)

grid[0].axis('off')

grid[0].set_title('dog')

imc = grid[1].imshow(x, cmap='hot', interpolation='nearest')

grid[1].axis('off')

grid[1].set_title('dog')

plt.colorbar(imc, cax=grid.cbar_axes[0])

oBDij.png

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐