Create BboxImage in Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, you will learn how to create a BboxImage in Matplotlib. A BboxImage can be used to position an image according to a bounding box. We will show how to create a BboxImage with Text and how to create a BboxImage for each colormap.

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 matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") 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 matplotlib/importing_matplotlib -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} matplotlib/figures_axes -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/conditional_statements -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/for_loops -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/tuples -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/importing_modules -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/using_packages -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/numerical_computing -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/data_visualization -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} python/build_in_functions -.-> lab-48667{{"`Create BboxImage in Matplotlib`"}} end

Import necessary libraries

We start by importing the necessary libraries for this tutorial. We will need matplotlib.pyplot, numpy, BboxImage, Bbox and TransformedBbox.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox

Create a BboxImage with Text

We start by creating a BboxImage with Text. We create a text object with the text() method and add it to the ax1 object. We then create a BboxImage object using the add_artist() method. We pass the get_window_extent method of the text object to the BboxImage constructor to get the bounding box for the text. We also pass a 1D array of shape (1, 256) to the data parameter of the BboxImage constructor to create an image.

fig, (ax1, ax2) = plt.subplots(ncols=2)

txt = ax1.text(0.5, 0.5, "test", size=30, ha="center", color="w")
ax1.add_artist(
    BboxImage(txt.get_window_extent, data=np.arange(256).reshape((1, -1))))

Create a BboxImage for each colormap

Next, we create a BboxImage for each colormap. We start by creating a list of all colormaps using the plt.colormaps method. We then create a for loop that iterates through the list of colormaps. For each colormap, we calculate the ix and iy position using the divmod() method. We then create a Bbox object using the Bbox.from_bounds() method. We pass the ix, iy, dx, and dy values to the Bbox.from_bounds() method to create the bounding box. We then create a TransformedBbox object using the Bbox object and the ax2.transAxes object. Finally, we create a BboxImage object using the add_artist() method. We pass the TransformedBbox object to the BboxImage constructor to create an image with the colormap.

cmap_names = sorted(m for m in plt.colormaps if not m.endswith("_r"))

ncol = 2
nrow = len(cmap_names) // ncol + 1

xpad_fraction = 0.3
dx = 1 / (ncol + xpad_fraction * (ncol - 1))

ypad_fraction = 0.3
dy = 1 / (nrow + ypad_fraction * (nrow - 1))

for i, cmap_name in enumerate(cmap_names):
    ix, iy = divmod(i, nrow)
    bbox0 = Bbox.from_bounds(ix*dx*(1+xpad_fraction),
                             1 - iy*dy*(1+ypad_fraction) - dy,
                             dx, dy)
    bbox = TransformedBbox(bbox0, ax2.transAxes)
    ax2.add_artist(
        BboxImage(bbox, cmap=cmap_name, data=np.arange(256).reshape((1, -1))))

Show the plot

Finally, we show the plot using the show() method.

plt.show()

Summary

In this lab, you learned how to create a BboxImage in Matplotlib. We created a BboxImage with Text and a BboxImage for each colormap. You can use this knowledge to create images with different bounding boxes and colormaps.

Other Python Tutorials you may like