J. O'connor
J. O'connor

Reputation: 43

Set one colorbar for two images/subplots, and another colorbar for third image in 3 panel figure

This MWE from the matplotlib doc is a useful reference.

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

plt.subplot(311)
plt.imshow(np.random.random((100, 100)))
plt.subplot(312)
plt.imshow(np.random.random((100, 100)))
plt.subplot(313)
plt.imshow(np.random.random((100, 100)))

plt.subplots_adjust(bottom=0.1, right=0.8, top=.9)
cax = plt.axes([0.85, 0.1, 0.075, 0.8])
plt.colorbar(cax=cax)

plt.show()

This produces:

enter image description here

My two main questions are:

  1. How do I get the first two plots to share a colorbar and the third to have its own?
  2. I don't really understand what 'cax' is doing or why the values are what they are.

Upvotes: 0

Views: 1217

Answers (1)

Redox
Redox

Reputation: 9967

As the question just says - two plots share a colorbar, you can either have the first two in the first row with a common colorbar, while the third will have another one, or you could do all 3 in separate columns with the first two sharing a colorbar.

Code for first option

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

fig, ax = plt.subplots()
plt.subplot(221) ## 2x2 plot, 1st item or in position 1,1
plt.imshow(np.random.random((100, 100)))
ax2 = plt.subplot(222)
im2 = ax2.imshow(np.random.random((100, 100)))
plt.colorbar(im2, ax=ax2)
ax3 = plt.subplot(223)
im3 = ax3.imshow(np.random.random((100, 100)))
plt.colorbar(im3, ax=ax3)

plt.show()

Plot

enter image description here

Option 2 code

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

fig, ax = plt.subplots(figsize=(5,6))
ax1 = plt.subplot(311) ## 3 rows and 1 column, position 1,1 =1
im = ax1.imshow(np.random.random((100, 100)))
ax2 = plt.subplot(312)
im = ax2.imshow(np.random.random((100, 100)))
ax3 = plt.subplot(313)
im3 = ax3.imshow(np.random.random((100, 100)))
plt.colorbar(im3, ax=ax3)
plt.colorbar(im, ax=[ax1, ax2], aspect = 40) ##Common colobar for ax1 and ax2; aspect used to set colorbar thickness/width

plt.show()

Plot

enter image description here

Although I have not used colorbar axis, it is the axis into which the colorbar is drawn, similar to what we have above in ax1, ax2, ax3 above. The numbers are used to specify where the colorbar should be located. Look at the last example here to see how the position is set. Hope this helps

Upvotes: 1

Related Questions