colorbar changes the size of subplot in python

非 Y 不嫁゛ 提交于 2021-02-16 13:57:47

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/60428817/colorbar-changes-the-size-of-subplot-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!