Creating Zoomed Inset with Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a popular data visualization library in Python. It provides many tools to create different types of plots and graphs. One of the useful features of Matplotlib is the ability to zoom in on a particular region of a plot, which can help to analyze data more closely. In this lab, we will learn how to create a zoomed inset 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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") 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-48787{{"`Creating Zoomed Inset with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} matplotlib/heatmaps -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/variables_data_types -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/strings -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/booleans -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/type_conversion -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/for_loops -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/lists -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/tuples -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/function_definition -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/importing_modules -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/numerical_computing -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/data_visualization -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} python/build_in_functions -.-> lab-48787{{"`Creating Zoomed Inset with Matplotlib`"}} end

Import necessary libraries

Before we start creating the zoomed inset, we need to import the necessary libraries. We will be using matplotlib.pyplot and numpy for this lab.

import matplotlib.pyplot as plt
import numpy as np

Create a figure and subplots

Next, we will create a figure and subplots to display our data. We will create two subplots side-by-side to show two different examples of zoomed insets.

fig, (ax, ax2) = plt.subplots(ncols=2, figsize=[6, 3])

Create a zoomed inset with a size bar

In the first subplot, we will create a zoomed inset with a size bar. This will show how to use the .zoomed_inset_axes method to create a zoomed inset.

## Set the aspect ratio of the plot to 1
ax.set_aspect(1)

## Create a zoomed inset in the upper right corner of the plot
axins = zoomed_inset_axes(ax, zoom=0.5, loc='upper right')

## Set the number of ticks on the inset axes
axins.yaxis.get_major_locator().set_params(nbins=7)
axins.xaxis.get_major_locator().set_params(nbins=7)

## Hide the tick labels on the inset axes
axins.tick_params(labelleft=False, labelbottom=False)

## Define a function to add a size bar to the plot
def add_sizebar(ax, size):
    asb = AnchoredSizeBar(ax.transData,
                          size,
                          str(size),
                          loc=8,
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False)
    ax.add_artist(asb)

## Add a size bar to the main plot and the inset plot
add_sizebar(ax, 0.5)
add_sizebar(axins, 0.5)

Create an image with an inset zoom and a marked inset

In the second subplot, we will create an image with an inset zoom and a marked inset. This will show how to use the .mark_inset method to mark the region of interest and connect it to the inset axes.

## Load sample data for the image
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")  ## 15x15 array
extent = (-3, 4, -4, 3)
Z2 = np.zeros((150, 150))
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z

## Display the image in the subplot
ax2.imshow(Z2, extent=extent, origin="lower")

## Create a zoomed inset in the upper left corner of the plot
axins2 = zoomed_inset_axes(ax2, zoom=6, loc=1)

## Display the image in the inset plot
axins2.imshow(Z2, extent=extent, origin="lower")

## Set the x and y limits of the inset plot to show the region of interest
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins2.set_xlim(x1, x2)
axins2.set_ylim(y1, y2)

## Set the number of ticks on the inset axes
axins2.yaxis.get_major_locator().set_params(nbins=7)
axins2.xaxis.get_major_locator().set_params(nbins=7)

## Hide the tick labels on the inset axes
axins2.tick_params(labelleft=False, labelbottom=False)

## Mark the region of interest and connect it to the inset axes
mark_inset(ax2, axins2, loc1=2, loc2=4, fc="none", ec="0.5")

Display the plot

Finally, we will display the plot using the plt.show() method.

plt.show()

Summary

In this lab, we learned how to create a zoomed inset using Matplotlib. We used the .zoomed_inset_axes and .mark_inset methods to create two different examples of zoomed insets. By using these methods, we can analyze data more closely and gain insights that may not be visible in the original plot.

Other Python Tutorials you may like