Annotating Matplotlib Plots with Coordinate Systems

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a powerful visualization tool that allows users to create a wide variety of plots and charts. Annotations are an important feature of Matplotlib that allow users to add text and arrows to their plots. In this tutorial, we will learn how to use different coordinate systems for annotations.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) 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/line_plots("`Line Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/text_annotations("`Text Annotations`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") 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-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} matplotlib/figures_axes -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} matplotlib/line_plots -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} matplotlib/text_annotations -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/variables_data_types -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/tuples -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/dictionaries -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/importing_modules -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/data_collections -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/numerical_computing -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/data_visualization -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} python/build_in_functions -.-> lab-48545{{"`Annotating Matplotlib Plots with Coordinate Systems`"}} end

Import Libraries

The first step is to import the necessary libraries. We will be using the matplotlib.pyplot library to create our plot and annotations.

import matplotlib.pyplot as plt
import numpy as np

Create Data

Next, we will create some data to plot. We will be using the numpy library to create a sine wave.

x = np.arange(0, 10, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)

Create the Plot

Now, we will create the plot using the matplotlib.pyplot library. We will set the x and y limits of the plot and then plot the data.

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)

Transform Coordinates

The next step is to transform the coordinates of the data and the display. We will use the ax.transData method to transform the data coordinates and the figure pixels coordinate system to transform the display coordinates.

xdata, ydata = 5, 0
xdisplay, ydisplay = ax.transData.transform((xdata, ydata))

Add Annotations

The final step is to add annotations to the plot. We will use the ax.annotate method to add text and arrows to the plot. We will also use the bbox and arrowprops parameters to style the annotations.

bbox = dict(boxstyle="round", fc="0.8")
arrowprops = dict(
    arrowstyle="->",
    connectionstyle="angle,angleA=0,angleB=90,rad=10")

offset = 72
ax.annotate(
    f'data = ({xdata:.1f}, {ydata:.1f})',
    (xdata, ydata),
    xytext=(-2*offset, offset), textcoords='offset points',
    bbox=bbox, arrowprops=arrowprops)
ax.annotate(
    f'display = ({xdisplay:.1f}, {ydisplay:.1f})',
    xy=(xdisplay, ydisplay), xycoords='figure pixels',
    xytext=(0.5*offset, -offset), textcoords='offset points',
    bbox=bbox, arrowprops=arrowprops)

Show the Plot

The final step is to show the plot using the plt.show() method.

plt.show()

Summary

In this tutorial, we learned how to use different coordinate systems for annotations in Matplotlib. We created a plot, transformed the data and display coordinates, and added annotations to the plot using the ax.annotate method. Annotations are an important feature of Matplotlib that allow users to add context and information to their plots.

Other Python Tutorials you may like