Matplotlib Image Visualization Techniques

MatplotlibMatplotlibBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK. In this lab, we will learn how to plot different types of images using Matplotlib.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") matplotlib/PlotCustomizationGroup -.-> matplotlib/grid_config("`Grid Configuration`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/FileHandlingGroup -.-> python/file_reading_writing("`Reading and Writing Files`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/with_statement -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} matplotlib/importing_matplotlib -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} matplotlib/figures_axes -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} matplotlib/line_plots -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} matplotlib/heatmaps -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} matplotlib/grid_config -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/variables_data_types -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/numeric_types -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/booleans -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/for_loops -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/lists -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/tuples -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/importing_modules -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/using_packages -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/standard_libraries -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/file_reading_writing -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/math_random -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/numerical_computing -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/data_visualization -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} python/build_in_functions -.-> lab-48779{{"`Matplotlib Image Visualization Techniques`"}} end

Import necessary libraries

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.cm as cm
from matplotlib.patches import PathPatch
from matplotlib.path import Path

Plot a bivariate normal distribution

## Generate a simple bivariate normal distribution
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

## Plot the distribution
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
               origin='lower', extent=[-3, 3, -3, 3],
               vmax=abs(Z).max(), vmin=-abs(Z).max())
plt.show()

Plot images of pictures

## Load a sample image
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
    image = plt.imread(image_file)

## Load another image using 256x256 16-bit integers.
w, h = 256, 256
with cbook.get_sample_data('s1045.ima.gz') as datafile:
    s = datafile.read()
A = np.frombuffer(s, np.uint16).astype(float).reshape((w, h))
extent = (0, 25, 0, 25)

## Plot both images
fig, ax = plt.subplot_mosaic([
    ['hopper', 'mri']
], figsize=(7, 3.5))

ax['hopper'].imshow(image)
ax['hopper'].axis('off')  ## clear x-axis and y-axis

im = ax['mri'].imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent)

markers = [(15.9, 14.5), (16.8, 15)]
x, y = zip(*markers)
ax['mri'].plot(x, y, 'o')

ax['mri'].set_title('MRI')

plt.show()

Interpolate images

## Interpolate the same array with three different interpolation methods
A = np.random.rand(5, 5)

fig, axs = plt.subplots(1, 3, figsize=(10, 3))
for ax, interp in zip(axs, ['nearest', 'bilinear', 'bicubic']):
    ax.imshow(A, interpolation=interp)
    ax.set_title(interp.capitalize())
    ax.grid(True)

plt.show()

Control image origin

## Specify whether images should be plotted with the array origin x[0, 0] in the upper left or lower right
x = np.arange(120).reshape((10, 12))

interp = 'bilinear'
fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5))
axs[0].set_title('blue should be up')
axs[0].imshow(x, origin='upper', interpolation=interp)

axs[1].set_title('blue should be down')
axs[1].imshow(x, origin='lower', interpolation=interp)
plt.show()

Show images using a clip path

## Show an image using a clip path
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]])
patch = PathPatch(path, facecolor='none')

fig, ax = plt.subplots()
ax.add_patch(patch)

im = ax.imshow(Z, interpolation='bilinear', cmap=cm.gray,
               origin='lower', extent=[-3, 3, -3, 3],
               clip_path=patch, clip_on=True)
im.set_clip_path(patch)

plt.show()

Summary

In this lab, we learned how to plot different types of images using Matplotlib. We plotted a bivariate normal distribution, images of pictures, interpolated images, and images using a clip path. We also learned how to control the image origin.

Other Matplotlib Tutorials you may like