0

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

without ax2 = ax.twinx()

with ax2 = ax.twinx()

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.

felipon
  • 5
  • 4

1 Answers1

0

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

enter image description here

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31
  • No, I did not know of its existence. It is very useful though and it works the way you show. There are two issues though: 1. It says in the documentation that 'Currently Constrained Layout is experimental. The behavior and API are subject to change, or the whole functionality may be removed without a deprecation period.' So is there a way to solve this without using this feature? 2. It does not work with my line defining 'cax'. Shouldn't it also work? – felipon Sep 30 '21 at 12:40
  • constrained_layout isn't going anywhere - experimental just means that the API could change. And no, constrained_layout does not work with axes_divider. – Jody Klymak Sep 30 '21 at 15:05