The problem is a bit hard to describe, but very easy to show. I create a grid with subplots on it, where the right column is filled by a tall subplot (approximately following this) which I want to use for the colourbar. Creating a new axis of a given size and using it for a colourbar is done in many code samples (see for example here), but it's not working for me.
Here's an example with a plot layout the same as my real plot that reproduces the problem:
import matplotlib.pyplot as plt
import matplotlib.colors as clt
import numpy as np
fig, axes = plt.subplots(3, 2, figsize=(15,8), tight_layout=True,
gridspec_kw={'width_ratios': [1, 0.02],
'height_ratios': [2, 1, 1]})
x, y = np.random.rand(500000), np.random.rand(500000)
counts, xedges, yedges, im = axes[0, 0].hist2d(x, y, bins=(149, 336), norm=clt.LogNorm(), cmap='inferno_r')
axes[1, 0].plot(np.random.rand(2184))
axes[2, 0].plot(np.random.rand(2184))
gs = axes[0, 1].get_gridspec()
for ax in axes[:, 1]:
ax.remove()
axbig = fig.add_subplot(gs[0:, -1])
bar = fig.colorbar(im, ax=axbig)
axes[0, 0].set_ylabel("2D histogram")
axes[1, 0].set_ylabel("unrelated data")
axes[2, 0].set_ylabel("other unrelated")
bar.set_label("colourbar")
(note that I use add_subplot(gs[0:, -1])
to make the tall subplot, but something like add_axes([0.8, 0.1, 0.03, 0.8])
has the same effect)
Notice how the colourbar is added as a tiny little new axis, onto the existing axis which I created for it. I would expect it to fill in the existing axis, as in this or this example. What's going wrong? I'm running matplotlib 3.3.1 from inside spyder 5.0.0 with python 3.8.