Create Matplotlib Arrow Reference Chart

PythonPythonBeginner
Practice Now

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

Introduction

This tutorial will walk you through the process of creating an arrow style reference chart using Matplotlib in Python. The chart will display the different arrow styles available in ~.Axes.annotate.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) 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/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) 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/line_plots("`Line Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/text_annotations("`Text Annotations`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/AdvancedTopicsGroup -.-> python/iterators("`Iterators`") python/AdvancedTopicsGroup -.-> python/regular_expressions("`Regular Expressions`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} matplotlib/importing_matplotlib -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} matplotlib/figures_axes -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} matplotlib/line_plots -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} matplotlib/text_annotations -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/variables_data_types -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/strings -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/type_conversion -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/conditional_statements -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/for_loops -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/lists -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/tuples -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/lambda_functions -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/importing_modules -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/standard_libraries -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/iterators -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/regular_expressions -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/data_collections -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/data_visualization -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} python/build_in_functions -.-> lab-48723{{"`Create Matplotlib Arrow Reference Chart`"}} end

Import Necessary Libraries

Import the necessary libraries to create the arrow style reference chart.

import inspect
import itertools
import re

import matplotlib.pyplot as plt

import matplotlib.patches as mpatches

Get Arrow Styles

Use mpatches.ArrowStyle.get_styles() to get all the arrow styles available in ~.Axes.annotate.

styles = mpatches.ArrowStyle.get_styles()

Set Up Figure

Set up the figure using plt.figure() and add_gridspec(). The figure will have a grid of 2 columns and n rows, where n is the number of arrow styles. Each cell in the grid will contain an arrow style and its default parameters.

ncol = 2
nrow = (len(styles) + 1) // ncol
axs = (plt.figure(figsize=(4 * ncol, 1 + nrow))
       .add_gridspec(1 + nrow, ncol,
                     wspace=.7, left=.1, right=.9, bottom=0, top=1).subplots())
for ax in axs.flat:
    ax.set_axis_off()
for ax in axs[0, :]:
    ax.text(0, .5, "arrowstyle",
            transform=ax.transAxes, size="large", color="tab:blue",
            horizontalalignment="center", verticalalignment="center")
    ax.text(.35, .5, "default parameters",
            transform=ax.transAxes,
            horizontalalignment="left", verticalalignment="center")

Plot Arrow Styles

Plot each arrow style in a cell of the grid, along with its default parameters. Use ax.annotate() to add the arrow style name and its default parameters to the cell.

for ax, (stylename, stylecls) in zip(axs[1:, :].T.flat, styles.items()):
    l, = ax.plot(.25, .5, "ok", transform=ax.transAxes)
    ax.annotate(stylename, (.25, .5), (-0.1, .5),
                xycoords="axes fraction", textcoords="axes fraction",
                size="large", color="tab:blue",
                horizontalalignment="center", verticalalignment="center",
                arrowprops=dict(
                    arrowstyle=stylename, connectionstyle="arc3,rad=-0.05",
                    color="k", shrinkA=5, shrinkB=5, patchB=l,
                ),
                bbox=dict(boxstyle="square", fc="w"))
    ## wrap at every nth comma (n = 1 or 2, depending on text length)
    s = str(inspect.signature(stylecls))[1:-1]
    n = 2 if s.count(',') > 3 else 1
    ax.text(.35, .5,
            re.sub(', ', lambda m, c=itertools.count(1): m.group()
                   if next(c) % n else '\n', s),
            transform=ax.transAxes,
            horizontalalignment="left", verticalalignment="center")

Display Chart

Display the arrow style reference chart using plt.show().

plt.show()

Summary

In this tutorial, you learned how to create an arrow style reference chart using Matplotlib in Python. You used mpatches.ArrowStyle.get_styles() to get all the arrow styles available in ~.Axes.annotate, set up a figure using plt.figure() and add_gridspec(), plotted each arrow style in a cell of the grid, and displayed the chart using plt.show().

Other Python Tutorials you may like