Home > OS >  twinx messes up colorbar of pcolormesh plot
twinx messes up colorbar of pcolormesh plot

Time:10-04

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

enter image description here

  • Related