I have encountered a problem when trying to plot some values on top of an image. The problem is that I cannot really place the colorbar properly. With properly I mean an image where I overlay a line plot. This line plot should have its yaxis on the right with its label and then further to the right should be the colorbar of the image.
Here is the reduced code that shows the problem:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
image = np.random.randint(10, size=100).reshape(10, 10)
fig, ax = plt.subplots()
# ax2 = ax.twinx() # -> Calling this messes up the colorbar
# ax2.plot(image.sum(0), 'r') # what I actually want to do but not needed for the error
im = ax.pcolormesh(image)
cax = make_axes_locatable(ax).append_axes('right', size="5%", pad=0.4)
cbar = fig.colorbar(im, cax=cax)
Below you can see the effect of ax2 = ax.twinx()
on the colorbar (I do not have enough reputation for the images so stackoverflow replaced it with links).
I have tried make_axes_locatable(ax).append_axes()
and also a combination with make_axes_locatable(ax).new_horizontal()
inspired by the answer to this question: Positioning the colorbar.
Looking into documentation of fig.colorbar()
I found the arguments ax
and cax
and played with them around. They do a lot, but not what I would like to.
I'm not sure what I'm doing wrong, could not find out on the internet and I'm thankful for any advice.
Did you try a normal colorbar with constrained_layout:
import matplotlib.pyplot as plt
import numpy as np
image = np.random.randint(10, size=100).reshape(10, 10)
fig, ax = plt.subplots(constrained_layout=True)
ax2 = ax.twinx()
ax2.plot(image.sum(0), 'r')
im = ax.pcolormesh(image)
cbar = fig.colorbar(im, ax=ax)
plt.show()