Matplotlib Rellenar entrex

MatplotlibMatplotlibBeginner
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

Matplotlib es una biblioteca de visualización de datos en Python. Proporciona una amplia variedad de herramientas para crear gráficos, diagramas y gráficas complejas y personalizables. Una de las herramientas más útiles proporcionadas por Matplotlib es la función fill_betweenx. Esta función se utiliza para rellenar el área entre dos curvas horizontales. En este tutorial, exploraremos la función fill_betweenx y aprenderemos cómo utilizarla para crear diferentes tipos de gráficos.

Consejos sobre la VM

Una vez finalizada la inicialización de 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 su retroalimentación 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"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/DataScienceandMachineLearningGroup(["Data Science and Machine Learning"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) matplotlib(("Matplotlib")) -.-> matplotlib/PlottingDataGroup(["Plotting Data"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("Importing Matplotlib") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("Understanding Figures and Axes") python/BasicConceptsGroup -.-> python/booleans("Booleans") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("Line Plots") python/DataStructuresGroup -.-> python/lists("Lists") 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-48735{{"Matplotlib Rellenar entrex"}} matplotlib/figures_axes -.-> lab-48735{{"Matplotlib Rellenar entrex"}} python/booleans -.-> lab-48735{{"Matplotlib Rellenar entrex"}} matplotlib/line_plots -.-> lab-48735{{"Matplotlib Rellenar entrex"}} python/lists -.-> lab-48735{{"Matplotlib Rellenar entrex"}} python/tuples -.-> lab-48735{{"Matplotlib Rellenar entrex"}} python/importing_modules -.-> lab-48735{{"Matplotlib Rellenar entrex"}} python/numerical_computing -.-> lab-48735{{"Matplotlib Rellenar entrex"}} python/data_visualization -.-> lab-48735{{"Matplotlib Rellenar entrex"}} end

Graficando un relleno simple entre curvas horizontales

En este paso, aprenderemos cómo utilizar la función fill_betweenx para crear un gráfico simple. Rellenaremos el área entre dos curvas.

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)

fig, ax = plt.subplots(figsize=(6, 6))

ax.fill_betweenx(y, x1, x2, color='green', alpha=0.5)
ax.plot(x1, y, color='blue')
ax.plot(x2, y, color='red')

plt.show()

Creando múltiples subgráficos

En este paso, aprenderemos cómo crear múltiples subgráficos y utilizar la función fill_betweenx para rellenar el área entre dos curvas horizontales en cada subgráfico.

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)

fig, [ax1, ax2, ax3] = plt.subplots(1, 3, sharey=True, figsize=(12, 4))

ax1.fill_betweenx(y, 0, x1, color='green', alpha=0.5)
ax1.plot(x1, y, color='blue')
ax1.set_title('Relleno entre (x1, 0)')

ax2.fill_betweenx(y, x1, 1, color='red', alpha=0.5)
ax2.plot(x1, y, color='blue')
ax2.set_title('Relleno entre (x1, 1)')

ax3.fill_betweenx(y, x1, x2, color='naranja', alpha=0.5)
ax3.plot(x1, y, color='blue')
ax3.plot(x2, y, color='rojo')
ax3.set_title('Relleno entre (x1, x2)')

plt.show()

Utilizando condiciones lógicas

En este paso, aprenderemos cómo utilizar condiciones lógicas para rellenar el área entre dos curvas horizontales.

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)

fig, ax = plt.subplots(figsize=(6, 6))

ax.plot(x1, y, color='black')
ax.plot(x2, y, color='black')

ax.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='green', alpha=0.5)
ax.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red', alpha=0.5)

plt.show()

Utilizando matrices con valores enmascarados

En este paso, aprenderemos cómo utilizar matrices con valores enmascarados para rellenar el área entre dos curvas horizontales.

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)
x2 = np.ma.masked_greater(x2, 1.0)

fig, ax = plt.subplots(figsize=(6, 6))

ax.plot(x1, y, color='black')
ax.plot(x2, y, color='black')

ax.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='verde', alpha=0.5)
ax.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='rojo', alpha=0.5)

plt.show()

Resumen

En este tutorial, aprendimos cómo utilizar la función fill_betweenx en Matplotlib para rellenar el área entre dos curvas horizontales. También aprendimos cómo crear múltiples subgráficos y utilizar condiciones lógicas y matrices con valores enmascarados para crear diferentes tipos de gráficos. Al utilizar la función fill_betweenx, podemos crear gráficos complejos y personalizables en Python.