Matplotlib

Matplotlib Tutorial – Chapter 8: Working with Images and Colors

📘 Matplotlib Tutorial – Chapter 8: Working with Images and Colors

Matplotlib is not just about charts — it’s a versatile library that can handle image processing and color visualization too. In this chapter, you’ll learn how to display images, apply different color schemes, and use colorbars to represent data values clearly.

✅ Understanding Image Handling in Matplotlib

Images in Matplotlib are represented as two-dimensional arrays where each element corresponds to a pixel’s intensity. These can be grayscale or RGB(A) images.


import matplotlib.pyplot as plt
import numpy as np

# Create a random image
image = np.random.rand(10, 10)
plt.imshow(image, cmap='viridis')
plt.colorbar()
plt.title("Random Image Display with Viridis Colormap")
plt.show()
  

The imshow() function displays image data, and the cmap argument specifies the colormap used to translate numbers into colors.

✅ Displaying Real Images

You can load and visualize real images easily using matplotlib.image or the Pillow (PIL) library.


import matplotlib.image as mpimg

img = mpimg.imread('example.jpg')
plt.imshow(img)
plt.axis('off')  # Hide axes
plt.title("Loaded Image using Matplotlib")
plt.show()
  

Matplotlib automatically detects whether an image is grayscale or RGB.

✅ Using Colormaps (cmap)

Colormaps define how numerical values are converted into color shades. Matplotlib includes dozens of ready-to-use colormaps such as viridis, plasma, cividis, gray, and inferno.


plt.imshow(image, cmap='plasma')
plt.colorbar()
plt.title("Plasma Colormap Example")
plt.show()
  
  • Sequential colormaps – best for low-to-high continuous data (Greens, Blues).
  • Diverging colormaps – useful when data has a midpoint (coolwarm, bwr).
  • Categorical colormaps – ideal for separate categories (tab10, Set3).

✅ Adding Colorbars

A colorbar shows how colors correspond to numeric values, improving the readability of visualizations.


plt.imshow(image, cmap='inferno')
plt.colorbar(label='Intensity Scale')
plt.title("Adding Colorbar Example")
plt.show()
  

To adjust the size or spacing of the colorbar, use parameters like fraction and pad:


plt.imshow(image, cmap='coolwarm')
plt.colorbar(fraction=0.046, pad=0.04)
plt.title("Custom Colorbar Size and Position")
plt.show()
  

✅ Grayscale and Transparency

For grayscale displays, use cmap='gray'. To add transparency, apply the alpha parameter.


plt.imshow(image, cmap='gray', alpha=0.8)
plt.title("Grayscale Image with Transparency")
plt.show()
  

✅ Custom Colormaps

You can create personalized colormaps using ListedColormap or reverse any existing one by appending _r.


from matplotlib.colors import ListedColormap

new_cmap = ListedColormap(['#000000', '#FF0000', '#FFFF00', '#00FF00'])
plt.imshow(image, cmap=new_cmap)
plt.title("Custom Listed Colormap Example")
plt.show()
  

✅ Color Normalization

Normalization maps data values to a defined range of colors, ensuring that your visuals represent data consistently even if the values vary widely.


from matplotlib import colors

norm = colors.Normalize(vmin=0, vmax=1)
plt.imshow(image, cmap='viridis', norm=norm)
plt.colorbar()
plt.title("Color Normalization Example")
plt.show()
  

✅ Summary

  • Use imshow() to render images.
  • Apply cmap for color transformation.
  • Add colorbar() for clear value representation.
  • Experiment with custom colormaps and normalization.

In the next chapter, we’ll move into 3D Plotting — where you’ll learn to visualize 3D data using mpl_toolkits.mplot3d.

Leave a Reply

Your email address will not be published. Required fields are marked *