Customizing Text Paths with Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

The Matplotlib TextPath is a module that enables the creation of a path that outlines the characters of a text. The resulting path can be used for several purposes, such as a clip path for an image. In this lab, you will learn how to use the TextPath module to create and customize text paths for images.

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/FunctionsGroup(["`Functions`"]) linux(("`Linux`")) -.-> linux/PackagesandSoftwaresGroup(["`Packages and Softwares`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/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/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") linux/PackagesandSoftwaresGroup -.-> linux/pip("`Python Package Installing`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") 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/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") 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/keyword_arguments -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} linux/pip -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} matplotlib/heatmaps -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/booleans -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/for_loops -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/lists -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/tuples -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/function_definition -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/default_arguments -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/importing_modules -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/using_packages -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/standard_libraries -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/classes_objects -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/constructor -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/polymorphism -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/encapsulation -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/numerical_computing -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/data_visualization -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} python/build_in_functions -.-> lab-48685{{"`Customizing Text Paths with Matplotlib`"}} end

Install Matplotlib

Before starting, you must have Matplotlib installed in your environment. You can install it via pip by running the following command in your terminal:

pip install matplotlib

Import Required Libraries

First, import the required libraries to create the TextPath.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.cbook import get_sample_data
from matplotlib.image import BboxImage
from matplotlib.offsetbox import (AnchoredOffsetbox, AnnotationBbox, AuxTransformBox)
from matplotlib.patches import PathPatch, Shadow
from matplotlib.text import TextPath
from matplotlib.transforms import IdentityTransform

Create a PathClippedImagePatch

Create a PathClippedImagePatch object to draw an image of a text path. Use the following code to create a PathClippedImagePatch object:

class PathClippedImagePatch(PathPatch):
    def __init__(self, path, bbox_image, **kwargs):
        super().__init__(path, **kwargs)
        self.bbox_image = BboxImage(
            self.get_window_extent, norm=None, origin=None)
        self.bbox_image.set_data(bbox_image)

    def set_facecolor(self, color):
        super().set_facecolor("none")

    def draw(self, renderer=None):
        self.bbox_image.set_clip_path(self._path, self.get_transform())
        self.bbox_image.draw(renderer)
        super().draw(renderer)

Create an Offset Box

Create an offset box using AuxTransformBox to add the PathClippedImagePatch object. Use the following code to create the offset box:

offsetbox = AuxTransformBox(IdentityTransform())
offsetbox.add_artist(p)

Create an Anchored Offset Box

Create an anchored offset box using AnnotationBbox to add the offset box and set its position. Use the following code to create the anchored offset box:

ao = AnchoredOffsetbox(loc='upper left', child=offsetbox, frameon=True,
                           borderpad=0.2)
ax1.add_artist(ao)

Add Another Text

Add another text to the image using PathPatch. Use the following code to add another text:

for usetex, ypos, string in [
            (False, 0.25, r"textpath supports mathtext"),
            (True, 0.05, r"textpath supports \TeX"),
    ]:
        text_path = TextPath((0, 0), string, size=20, usetex=usetex)

        p1 = PathPatch(text_path, ec="w", lw=3, fc="w", alpha=0.9)
        p2 = PathPatch(text_path, ec="none", fc="k")

        offsetbox2 = AuxTransformBox(IdentityTransform())
        offsetbox2.add_artist(p1)
        offsetbox2.add_artist(p2)

        ab = AnnotationBbox(offsetbox2, (0.95, ypos),
                            xycoords='axes fraction',
                            boxcoords="offset points",
                            box_alignment=(1., 0.),
                            frameon=False,
                            )
        ax1.add_artist(ab)

Show the Image

Show the final image using the following code:

ax1.imshow([[0, 1, 2], [1, 2, 3]], cmap=plt.cm.gist_gray_r,
               interpolation="bilinear", aspect="auto")
plt.show()

Summary

In this lab, you learned how to use the Matplotlib TextPath module to create and customize text paths for images. By following the steps outlined in this lab, you can create images with custom text paths that are useful for a variety of purposes.

Other Python Tutorials you may like