4

I tried to plot two images next to each other with one corresponding colorbar for both of them. My code is

plt.figure(1)
plt.subplot (121)
plt.title('1')
plt.imshow(matrix_lg, interpolation='bilinear', cmap=plt.cm.jet, vmin=np.log10(minVal), vmax = np.log10(maxVal))
plt.subplot(122)
plt.title('2')
plt.imshow(matrix_lg, interpolation='bilinear', cmap=plt.cm.jet, vmin=np.log10(minVal), vmax = np.log10(maxVal))
plt.colorbar()

Python now attaches the colorbar to the second subplot and shrinks it therefore. But I want both plots to be the same size. How can I detach the colorbar of the subplots?

enter image description here

1 Answer 1

4

you can create a separate Axes instance for the colorbar

import matplotlib.pyplot as plt
import numpy as np

plt.figure(1)
# Create room on the right
plt.gcf().subplots_adjust(right=0.8)

plt.subplot (121)
plt.title('1')
plt.imshow(np.random.rand(10,10), interpolation='bilinear', cmap=plt.cm.jet)
plt.subplot(122)
plt.title('2')
plt.imshow(np.random.rand(10,10), interpolation='bilinear', cmap=plt.cm.jet)

# Make a new Axes instance
cbar_ax = plt.gcf().add_axes([0.85, 0.15, 0.05, 0.7])
plt.colorbar(cax=cbar_ax)

plt.show()

enter image description here

EDIT:

you can change the height of the colorbar to be more like the height of the plots by changing the add_axes command. That takes a rectangle as the argument [left, bottom, width, height], so just change the bottom and height to suit your needs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.