Creating Donuts Using path.Path and patches.PathPatch

PythonPythonBeginner
Practice Now

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

Introduction

In this tutorial, we will create a donut using Matplotlib's ~.path.Path and ~.patches.PathPatch. We will use the make_circle() function to create the circle and concatenate the inside and outside subpaths together to create the donut.

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/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/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) 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/PlotCustomizationGroup -.-> matplotlib/text_annotations("`Text Annotations`") 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/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") 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 python/comments -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} matplotlib/importing_matplotlib -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} matplotlib/figures_axes -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} matplotlib/text_annotations -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/conditional_statements -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/for_loops -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/lists -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/tuples -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/sets -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/function_definition -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/importing_modules -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/catching_exceptions -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/numerical_computing -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/data_visualization -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} python/build_in_functions -.-> lab-48693{{"`Creating Donuts Using path.Path and patches.PathPatch`"}} end

Importing Necessary Libraries

We will start by importing the necessary libraries for this tutorial.

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

Defining Helper Function

We will define a helper function wise() to determine the orientation of the path.

def wise(v):
    if v == 1:
        return "CCW"
    else:
        return "CW"

Creating the Circle

We will create the circle using the make_circle() function. The function takes the radius of the circle as input and returns the x and y coordinates of the circle.

def make_circle(r):
    t = np.arange(0, np.pi * 2.0, 0.01)
    t = t.reshape((len(t), 1))
    x = r * np.cos(t)
    y = r * np.sin(t)
    return np.hstack((x, y))

Creating the Donut

We will create the donut by concatenating the inside and outside subpaths together. We will use codes to specify the type of each vertex (MOVETO, LINETO, etc). We will then create a Path object using mpath.Path and a PathPatch object using mpatches.PathPatch. We will finally add the PathPatch object to the Axes object using ax.add_patch().

Path = mpath.Path
fig, ax = plt.subplots()

inside_vertices = make_circle(0.5)
outside_vertices = make_circle(1.0)
codes = np.ones(
    len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
codes[0] = mpath.Path.MOVETO

for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):
    ## Concatenate the inside and outside subpaths together, changing their
    ## order as needed
    vertices = np.concatenate((outside_vertices[::outside],
                               inside_vertices[::inside]))
    ## Shift the path
    vertices[:, 0] += i * 2.5
    ## The codes will be all "LINETO" commands, except for "MOVETO"s at the
    ## beginning of each subpath
    all_codes = np.concatenate((codes, codes))
    ## Create the Path object
    path = mpath.Path(vertices, all_codes)
    ## Add plot it
    patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')
    ax.add_patch(patch)

    ax.annotate(f"Outside {wise(outside)},\nInside {wise(inside)}",
                (i * 2.5, -1.5), va="top", ha="center")

ax.set_xlim(-2, 10)
ax.set_ylim(-3, 2)
ax.set_title('Mmm, donuts!')
ax.set_aspect(1.0)
plt.show()

Summary

In this tutorial, we learned how to create a donut using Matplotlib's ~.path.Path and ~.patches.PathPatch. We used the make_circle() function to create the circle and concatenated the inside and outside subpaths together to create the donut. We also learned how to specify the type of each vertex and create a Path object using mpath.Path. Finally, we learned how to create a PathPatch object using mpatches.PathPatch and add it to the Axes object using ax.add_patch().

Summary

Congratulations! You have completed the Creating Donuts Using ~.path.Path and ~.patches.PathPatch lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like