Drawing Shapes with Matplotlib in Python

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to draw various shapes using Matplotlib library in Python. Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK.

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`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/BasicConceptsGroup -.-> matplotlib/saving_figures("`Saving Figures to File`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} matplotlib/figures_axes -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} matplotlib/saving_figures -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} python/for_loops -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} python/lists -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} python/tuples -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} python/importing_modules -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} python/data_visualization -.-> lab-48554{{"`Drawing Shapes with Matplotlib in Python`"}} end

Import Libraries

Before we start using Matplotlib, we need to import the necessary libraries.

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.path as mpath

Define Shapes

We will define the shapes we want to draw using Matplotlib. In this example, we will draw a circle, a rectangle, a wedge, a regular polygon, an ellipse, an arrow, a path patch, and a fancy box patch.

shapes = [
    mpatches.Circle((0, 0), 0.1, ec="none"),
    mpatches.Rectangle((-0.025, -0.05), 0.05, 0.1, ec="none"),
    mpatches.Wedge((0, 0), 0.1, 30, 270, ec="none"),
    mpatches.RegularPolygon((0, 0), 5, radius=0.1),
    mpatches.Ellipse((0, 0), 0.2, 0.1),
    mpatches.Arrow(-0.05, -0.05, 0.1, 0.1, width=0.1),
    mpatches.PathPatch(mpath.Path([(0, 0), (0.5, 0.5), (1, 0)], [1, 2, 2]), ec="none"),
    mpatches.FancyBboxPatch((-0.025, -0.05), 0.05, 0.1, ec="none",
                            boxstyle=mpatches.BoxStyle("Round", pad=0.02)),
]

Draw Shapes

We will now draw the shapes using Matplotlib by iterating through the shapes list and adding them to the plot.

fig, ax = plt.subplots()
for shape in shapes:
    ax.add_artist(shape)
plt.xlim([-0.5, 1.5])
plt.ylim([-0.5, 1.5])
plt.axis('off')
plt.show()

Customize Shapes

We can customize the shapes by setting various properties such as color, edge color, and alpha.

shapes = [
    mpatches.Circle((0, 0), 0.1, color='red', alpha=0.5),
    mpatches.Rectangle((-0.025, -0.05), 0.05, 0.1, ec="none", color='green', alpha=0.5),
    mpatches.Wedge((0, 0), 0.1, 30, 270, ec="none", color='blue', alpha=0.5),
    mpatches.RegularPolygon((0, 0), 5, radius=0.1, color='orange', alpha=0.5),
    mpatches.Ellipse((0, 0), 0.2, 0.1, color='purple', alpha=0.5),
    mpatches.Arrow(-0.05, -0.05, 0.1, 0.1, width=0.1, color='yellow', alpha=0.5),
    mpatches.PathPatch(mpath.Path([(0, 0), (0.5, 0.5), (1, 0)], [1, 2, 2]), ec="none", color='pink', alpha=0.5),
    mpatches.FancyBboxPatch((-0.025, -0.05), 0.05, 0.1, ec="none", color='brown', alpha=0.5,
                            boxstyle=mpatches.BoxStyle("Round", pad=0.02)),
]

fig, ax = plt.subplots()
for shape in shapes:
    ax.add_artist(shape)
plt.xlim([-0.5, 1.5])
plt.ylim([-0.5, 1.5])
plt.axis('off')
plt.show()

Save Plot

We can save the plot as an image file using the savefig function.

fig, ax = plt.subplots()
for shape in shapes:
    ax.add_artist(shape)
plt.xlim([-0.5, 1.5])
plt.ylim([-0.5, 1.5])
plt.axis('off')
plt.savefig('shapes.png')

Summary

In this lab, we learned how to draw various shapes using Matplotlib library in Python. We learned how to define shapes, draw shapes, customize shapes, and save the plot as an image file. Matplotlib provides an easy-to-use API for drawing various types of plots and is widely used in data visualization.

Other Python Tutorials you may like