Tutorial de creación de leyendas con Matplotlib

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

Matplotlib es una biblioteca de trazado para el lenguaje de programación Python y su extensión matemática numérica NumPy. En este tutorial, aprenderemos cómo crear una leyenda simple con Matplotlib.

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 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"]) matplotlib(("Matplotlib")) -.-> matplotlib/PlotCustomizationGroup(["Plot Customization"]) python(("Python")) -.-> python/DataScienceandMachineLearningGroup(["Data Science and Machine Learning"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("Importing Matplotlib") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("Understanding Figures and Axes") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("Line Plots") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") matplotlib/PlotCustomizationGroup -.-> matplotlib/line_styles_colors("Customizing Line Styles and Colors") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("Legend Configuration") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} matplotlib/figures_axes -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} matplotlib/line_plots -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} python/lists -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} python/tuples -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} matplotlib/line_styles_colors -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} matplotlib/legend_config -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} python/importing_modules -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} python/data_visualization -.-> lab-48942{{"Tutorial de creación de leyendas con Matplotlib"}} end

Importar Matplotlib

Para utilizar Matplotlib, primero debemos importarlo.

import matplotlib.pyplot as plt

Crear una figura y ejes

Necesitamos crear una figura y ejes para trazar nuestros datos.

fig, ax = plt.subplots()

Trazar los datos

Podemos trazar nuestros datos utilizando la función plot().

line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4)

Crear la primera leyenda

Podemos crear una leyenda para la primera línea utilizando la función legend().

first_legend = ax.legend(handles=[line1], loc='upper right')

Agregar la primera leyenda

Debemos agregar la primera leyenda a la gráfica utilizando la función add_artist().

ax.add_artist(first_legend)

Crear la segunda leyenda

Podemos crear otra leyenda para la segunda línea utilizando la función legend().

ax.legend(handles=[line2], loc='lower right')

Mostrar la gráfica

Podemos mostrar la gráfica utilizando la función show().

plt.show()

Resumen

En este tutorial, aprendimos cómo crear una leyenda simple con Matplotlib. Importamos Matplotlib, creamos una figura y ejes, tracamos los datos y creamos y agregamos dos leyendas a la gráfica. Finalmente, mostramos la gráfica utilizando la función show().