I'm trying to get a colorbar for an image, which is supposed to have the same height as the image. There are many solutions suggested here, but none of them work for an image which has an aspect ratio smaller than 1.
If you use the accepted answer from the linked question like this...
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)), aspect = 0.4375)
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
plt.savefig("asdf.png", bbox_inches = "tight")
... (Note the aspect in imshow call!), I get this:
Leaving aspect out, it works just fine, but for my data, I need to set the aspect ratio, as the step size for the x-axis is much larger than for the y-axis.
Other solutions, like plt.colorbar(im,fraction=0.046, pad=0.04)
or adding a seperate axis don't work either and produce similiar results.
How do I get the colorbar to have the same height in this case?
I finally found a solution here:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
...
fig, ax = plt.subplots(1, 1)
im = ax.imshow(data, aspect = aspectRatio)
axins = inset_axes(ax, width = "5%", height = "100%", loc = 'lower left',
bbox_to_anchor = (1.02, 0., 1, 1), bbox_transform = ax.transAxes,
borderpad = 0)
fig.colorbar(im, cax = axins)
... where data
is your array of values and 1.02
is the padding between the figure and the colorbar.
This creates colorbars with perfect height, regardless of the aspect ratio. No fiddling with magic numbers or anything of that sort.