Placing Text Boxes in Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

In data visualization, it is often necessary to add annotations to plots to provide additional information to the audience. One way to do this is by adding text boxes to a plot. In Matplotlib, it is possible to place text boxes in axes coordinates, so the text doesn't move around with changes in x or y limits. You can also use the bbox property of text to surround the text with a ~matplotlib.patches.Patch instance.

In this lab, we will learn how to place text boxes in Matplotlib using Python.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) 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`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/histograms("`Histograms`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") 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-48868{{"`Placing Text Boxes in Matplotlib`"}} matplotlib/figures_axes -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} matplotlib/histograms -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/variables_data_types -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/tuples -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/sets -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/importing_modules -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/standard_libraries -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/math_random -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/data_collections -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/numerical_computing -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/data_visualization -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} python/build_in_functions -.-> lab-48868{{"`Placing Text Boxes in Matplotlib`"}} end

Import necessary libraries

Before we can start adding text boxes to our plots, we need to import the necessary libraries. In this example, we will be using matplotlib.pyplot and numpy.

import matplotlib.pyplot as plt
import numpy as np

Create data

For this example, we will create a random dataset using numpy.random.randn().

np.random.seed(19680801)
x = 30*np.random.randn(10000)
mu = x.mean()
median = np.median(x)
sigma = x.std()

Create a histogram

Next, we will create a histogram of the data using matplotlib.pyplot.hist().

fig, ax = plt.subplots()
ax.hist(x, 50)

Create text for the text box

We will create a string containing the mean, median, and standard deviation of our data.

textstr = '\n'.join((
    r'$\mu=%.2f$' % (mu, ),
    r'$\mathrm{median}=%.2f$' % (median, ),
    r'$\sigma=%.2f$' % (sigma, )))

Create the text box properties

We will create a dictionary containing the properties for the text box. In this example, we will use a rounded box with a wheat-colored face and an alpha of 0.5.

props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

Add the text box to the plot

Finally, we will add the text box to the plot using matplotlib.pyplot.text(). We will specify the location of the text box in axes coordinates and use the bbox parameter to add the box properties.

ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=props)

Display the plot

We will display the plot using matplotlib.pyplot.show().

plt.show()

Summary

In this lab, we learned how to add text boxes to a plot in Matplotlib using Python. We used the matplotlib.pyplot.text() function to add the text box and specified the location of the box in axes coordinates. We also used the bbox property to add a rounded box around the text and set the box properties using a dictionary. This technique can be used to add annotations to plots and provide additional information to the audience.

Other Python Tutorials you may like