Open In App

Imshow with two colorbars under Matplotlib

In this article, we will learn how to use Imshow with two colorbars under Matplotlib. Let’s discuss some concepts :

A simple Imshow() with one colorbar






# import libraries
import matplotlib.pyplot as plt
import numpy as np
  
# create image = 10x10 array
img = np.random.randint(-100, 100, (10, 10))
  
# make plot
fig, ax = plt.subplots()
  
# show image
shw = ax.imshow(img)
  
# make bar
bar = plt.colorbar(shw)
  
# show plot with labels
plt.xlabel('X Label')
plt.ylabel('Y Label')
bar.set_label('ColorBar')
plt.show()

Output :



In the above output, we can see that there is one colorbar with values ranges from -100 to 100. This is not looking effective and not clear the difference of small positive values to larger positive values similarly not clear the difference of small negative values to larger negative values. Here, we divide colorbar in two parts :

With different colors, which help us to understand the plot clearly and effectively. Below all steps are mentioned for such work.

Steps Needed:

  1. Import libraries (matplotlib)
  2. Create / load image data
  3. Masked array to positive and negative values
  4. Make plot using subplot() method
  5. Show image using imshow() method
  6. Make bars using matplotlib.pyplot.colorbar() method
  7. Show plot with labels

Example:




# import libraries
import matplotlib.pyplot as plt
import numpy as np
from numpy.ma import masked_array
  
# create image = 10x10 array
img = np.random.randint(-100, 100, (10, 10))
  
# masked array to positive and negative values
neg_img = masked_array(img, img >= 0)
pos_img = masked_array(img, img < 0)
  
# make plot
fig, ax = plt.subplots()
  
# show image
shw1 = ax.imshow(neg_img, cmap=plt.cm.Reds)
shw2 = ax.imshow(pos_img, cmap=plt.cm.winter)
  
# make bars
bar1 = plt.colorbar(shw1)
bar2 = plt.colorbar(shw2)
  
# show plot with labels
plt.xlabel('X Label')
plt.ylabel('Y Label')
bar1.set_label('ColorBar 1')
bar2.set_label('ColorBar 2')
plt.show()

Output :


Article Tags :