When creating and removing a colorbar with a ScalarMappable, the axes size unexpectedly changes, whereas removing a colorbar linked to a plotted pcolormesh does not affect the axes size.
Code for reproduction
importnumpyasnpimportmatplotlib.pyplotaspltfrommatplotlibimportcm, colorsX, Y=np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128))
Z= (1-X/2+X**5+Y**3) *np.exp(-X**2-Y**2)
fig, ax=plt.subplots()
pc=ax.pcolormesh(X, Y, Z, vmin=-1, vmax=1, cmap='RdBu_r')
width, height=ax.get_window_extent().width, ax.get_window_extent().heightcbar=fig.colorbar(pc, ax=ax); cbar.remove() # this does not change the axes sizeassertax.get_window_extent().width==widthandax.get_window_extent().height==height# passcbar=fig.colorbar(cm.ScalarMappable(norm=colors.NoNorm(), cmap=plt.get_cmap("viridis")), ax=ax); cbar.remove() # this unexpectedly changes the axes sizeassertax.get_window_extent().width==widthandax.get_window_extent().height==height# fail
Activity
anntzer commented on Feb 5, 2026
I think this is a duplicate of #22257 and being worked on at #31040?