Sombra regiones con fill_between

PythonPythonBeginner
Practicar Ahora

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

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

En este laboratorio, aprenderemos cómo sombrear regiones en un gráfico de Matplotlib utilizando la función fill_between. Esto es útil para resaltar áreas específicas del gráfico, como regiones donde se cumple una cierta condición.

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("Matplotlib")) -.-> matplotlib/BasicConceptsGroup(["Basic Concepts"]) matplotlib(("Matplotlib")) -.-> matplotlib/PlottingDataGroup(["Plotting Data"]) 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/PlottingDataGroup -.-> matplotlib/line_plots("Line Plots") matplotlib/PlottingDataGroup -.-> matplotlib/fill_between("Fill Between Plots") python/DataStructuresGroup -.-> python/tuples("Tuples") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("Numerical Computing") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48948{{"Sombra regiones con fill_between"}} matplotlib/figures_axes -.-> lab-48948{{"Sombra regiones con fill_between"}} matplotlib/line_plots -.-> lab-48948{{"Sombra regiones con fill_between"}} matplotlib/fill_between -.-> lab-48948{{"Sombra regiones con fill_between"}} python/tuples -.-> lab-48948{{"Sombra regiones con fill_between"}} python/importing_modules -.-> lab-48948{{"Sombra regiones con fill_between"}} python/numerical_computing -.-> lab-48948{{"Sombra regiones con fill_between"}} python/data_visualization -.-> lab-48948{{"Sombra regiones con fill_between"}} end

Importar las bibliotecas necesarias

Comenzaremos importando las bibliotecas necesarias para este laboratorio, que son numpy y matplotlib.pyplot.

import numpy as np
import matplotlib.pyplot as plt

Crear datos

Vamos a crear algunos datos para utilizar en nuestro gráfico. En este ejemplo, crearemos una onda senoidal.

t = np.arange(0.0, 2, 0.01)
s = np.sin(2*np.pi*t)

Crear el gráfico

Ahora crearemos el gráfico utilizando matplotlib.pyplot. Graficaremos la onda senoidal y agregaremos una línea horizontal en y = 0.

fig, ax = plt.subplots()

ax.plot(t, s, color='black')
ax.axhline(0, color='black')

Sombra las regiones

Utilizaremos fill_between para sombrear las regiones por encima y por debajo de la línea horizontal donde la onda senoidal es positiva y negativa, respectivamente.

ax.fill_between(t, 1, where=s > 0, facecolor='green', alpha=.5)
ax.fill_between(t, -1, where=s < 0, facecolor='red', alpha=.5)

Muestra el gráfico

Finalmente, mostraremos el gráfico utilizando plt.show().

plt.show()

Resumen

En este laboratorio, aprendimos cómo sombrear regiones en un gráfico de Matplotlib utilizando la función fill_between. Esta es una herramienta útil para resaltar áreas específicas del gráfico. Esperamos que hayas encontrado este laboratorio útil.