Creating a Polygon in Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a Python library used for data visualization. In this lab, we will be using Matplotlib to create a polygon programmatically or interactively. The polygon can be used to highlight a region of interest or to mask out a certain area of a plot.

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/InteractiveFeaturesGroup(["`Interactive Features`"]) 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/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/InteractiveFeaturesGroup -.-> matplotlib/interactive_backends("`Interactive Backends`") matplotlib/InteractiveFeaturesGroup -.-> matplotlib/widgets_sliders("`Widgets and Sliders`") 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/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} matplotlib/figures_axes -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} matplotlib/interactive_backends -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} matplotlib/widgets_sliders -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/for_loops -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/lists -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/tuples -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/lambda_functions -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/importing_modules -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/using_packages -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/data_visualization -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} python/build_in_functions -.-> lab-48878{{"`Creating a Polygon in Matplotlib`"}} end

Import Required Libraries

Before we start working with Matplotlib, we need to import the necessary libraries. We will be using matplotlib.pyplot and matplotlib.widgets in this lab.

import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector

Create a Polygon Programmatically

To create a polygon programmatically, we need to create a Figure object and an Axes object. Then, we can create a PolygonSelector object and add vertices to it. Finally, we can plot the polygon on the Axes.

fig, ax = plt.subplots()
selector = PolygonSelector(ax, lambda *args: None)

## Add three vertices
selector.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)]

## Plot the polygon
ax.add_patch(plt.Polygon(selector.verts, alpha=0.3))
plt.show()

Create a Polygon Interactively

To create a polygon interactively, we need to create a Figure object and an Axes object. Then, we can create a PolygonSelector object and add vertices to it by clicking on the plot. We can also use the shift and ctrl keys to move the vertices.

fig, ax = plt.subplots()
selector = PolygonSelector(ax, lambda *args: None)

print("Click on the figure to create a polygon.")
print("Press the 'esc' key to start a new polygon.")
print("Try holding the 'shift' key to move all of the vertices.")
print("Try holding the 'ctrl' key to move a single vertex.")

plt.show()

Putting It All Together

Let's create a complete example that includes both creating a polygon programmatically and interactively.

import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector

## Create a figure and axes
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))

## Create a PolygonSelector object and add vertices
selector1 = PolygonSelector(ax1, lambda *args: None)
selector1.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)]

## Plot the polygon
ax1.add_patch(plt.Polygon(selector1.verts, alpha=0.3))

## Create another PolygonSelector object for interactive creation
selector2 = PolygonSelector(ax2, lambda *args: None)

print("Click on the figure to create a polygon.")
print("Press the 'esc' key to start a new polygon.")
print("Try holding the 'shift' key to move all of the vertices.")
print("Try holding the 'ctrl' key to move a single vertex.")

plt.show()

Summary

In this lab, we learned how to create a polygon programmatically and interactively using Matplotlib. We also learned how to add vertices to a PolygonSelector object and plot the resulting polygon on an Axes. This knowledge can be useful for highlighting regions of interest or masking out certain areas in a plot.

Other Python Tutorials you may like