jaroh24
jaroh24

Reputation: 45

How to add a colorbar to one subplot axes

I'm trying to create a figure using matplotlib, but it's not working as smoothly as I expected. I would like to create a composite figure with 4 images on the top row, and 1 long image directly below the 4 images. I want to to add a colorbar only for the bottom image, however, it's throwing errors.

import numpy as np
import matplotlib.pyplot as plt

img = np.random.rand(25, 20)
img2 = np.random.rand(25, 100)

fig = plt.figure(figsize=(12.8, 8.6),
#           gridspec_kw={'height_ratios':[1, 1.5],
#                     'wspace':0.1, 'hspace':0.1}
          )

im0 = plt.subplot(2,4,1)
im0.imshow(img, aspect='equal')
im0.axis('off')

im1 = plt.subplot(2,4,2)
im1.imshow(img, aspect='equal')
im1.axis('off')

im2 = plt.subplot(2,4,3)
im2.imshow(img, aspect='equal')
im2.axis('off')

im3 = plt.subplot(2,4,4)
im3.imshow(img, aspect='equal')
im3.axis('off')

im4 = plt.subplot(2,1,2)
im4.imshow(img2, aspect='equal')
im4.axis('off')

# cbar = fig.colorbar(im4)

plt.show()

enter image description here

Uncommenting cbar = fig.colorbar(im4) results in:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-170-91eaa4089d9f> in <module>
     27 im4.axis('off')
     28 
---> 29 cbar = fig.colorbar(im4)
     30 
     31 plt.show()

e:\Anaconda3\lib\site-packages\matplotlib\figure.py in colorbar(self, mappable, cax, ax, use_gridspec, **kw)
   1171                              'panchor']
   1172         cb_kw = {k: v for k, v in kw.items() if k not in NON_COLORBAR_KEYS}
-> 1173         cb = cbar.Colorbar(cax, mappable, **cb_kw)
   1174 
   1175         self.sca(current_ax)

e:\Anaconda3\lib\site-packages\matplotlib\colorbar.py in __init__(self, ax, mappable, **kwargs)
   1169         # Ensure the given mappable's norm has appropriate vmin and vmax set
   1170         # even if mappable.draw has not yet been called.
-> 1171         if mappable.get_array() is not None:
   1172             mappable.autoscale_None()
   1173 

AttributeError: 'AxesSubplot' object has no attribute 'get_array'

Upvotes: 1

Views: 9253

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62533

  • Using the example from Axes Divider
  • Assign the plot to a separate object.
    • im is a <class 'matplotlib.image.AxesImage'>
    • im4 is a <class 'matplotlib.axes._subplots.AxesSubplot'>
im4 = plt.subplot(2,1,2)

# assign plot to a new object
im = im4.imshow(img2, aspect='equal')

# add the bar
cbar = plt.colorbar(im)

im4.axis('off')

plt.show()

enter image description here

Upvotes: 1

Related Questions