Creando Anillos Usando path.Path y patches.PathPatch

Beginner

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

Introducción

En este tutorial, crearemos un anillo usando ~.path.Path y ~.patches.PathPatch de Matplotlib. Usaremos la función make_circle() para crear el círculo y concatenar los subcaminos internos y externos juntos para crear el anillo.

Consejos sobre la VM

Una vez que se haya iniciado la VM, haga clic en la esquina superior izquierda para cambiar a la pestaña Cuaderno y acceder a Jupyter Notebook para practicar.

A veces, es posible que tenga que esperar unos segundos a que Jupyter Notebook termine de cargarse. La validación de las operaciones no se puede automatizar debido a las limitaciones de Jupyter Notebook.

Si tiene problemas durante el aprendizaje, no dude en preguntar a Labby. Deje sus comentarios después de la sesión y lo resolveremos rápidamente para usted.

Importando las bibliotecas necesarias

Empezaremos importando las bibliotecas necesarias para este tutorial.

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

Definiendo una función auxiliar

Definiremos una función auxiliar wise() para determinar la orientación del camino.

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

Creando el círculo

Crearemos el círculo usando la función make_circle(). La función toma el radio del círculo como entrada y devuelve las coordenadas x e y del círculo.

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))

Creando el anillo

Crearemos el anillo concatenando los subcaminos interior y exterior. Usaremos codes para especificar el tipo de cada vértice (MOVETO, LINETO, etc.). Luego crearemos un objeto Path usando mpath.Path y un objeto PathPatch usando mpatches.PathPatch. Finalmente, agregaremos el objeto PathPatch al objeto Axes usando 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"Fuera {wise(outside)},\nDentro {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()

Resumen

En este tutorial, aprendimos cómo crear un anillo usando ~.path.Path y ~.patches.PathPatch de Matplotlib. Usamos la función make_circle() para crear el círculo y concatenamos los subcaminos interior y exterior para crear el anillo. También aprendimos cómo especificar el tipo de cada vértice y crear un objeto Path usando mpath.Path. Finalmente, aprendimos cómo crear un objeto PathPatch usando mpatches.PathPatch y agregarlo al objeto Axes usando ax.add_patch().

Resumen

¡Felicitaciones! Has completado el laboratorio de Creación de Anillos usando ~.path.Path y ~.patches.PathPatch. Puedes practicar más laboratorios en LabEx para mejorar tus habilidades.