Creando texto y texto matemático con Pyplot

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 poderosa biblioteca de visualización de datos en Python. Proporciona una amplia gama de herramientas para crear gráficos y diagramas en Python. En este tutorial, aprenderemos cómo crear texto y mathtext usando pyplot.

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 operaciones no puede automatizarse 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/PlotCustomizationGroup(["Plot Customization"]) python(("Python")) -.-> python/DataScienceandMachineLearningGroup(["Data Science and Machine Learning"]) 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"]) 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/titles_labels("Adding Titles and Labels") 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-48888{{"Creando texto y texto matemático con Pyplot"}} matplotlib/figures_axes -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} matplotlib/line_plots -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} python/lists -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} python/tuples -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} matplotlib/titles_labels -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} python/importing_modules -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} python/numerical_computing -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} python/data_visualization -.-> lab-48888{{"Creando texto y texto matemático con Pyplot"}} end

Importar las bibliotecas necesarias

En primer lugar, necesitamos importar las bibliotecas necesarias. Importaremos las bibliotecas numpy y matplotlib.pyplot.

import matplotlib.pyplot as plt
import numpy as np

Crear datos

A continuación, crearemos los datos para el gráfico. Crearemos una onda senoidal utilizando la biblioteca numpy.

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

Trazar el gráfico

Ahora, trazaremos el gráfico utilizando el método plot() de la biblioteca pyplot.

plt.plot(t, s)

Agregar texto al gráfico

Podemos agregar texto al gráfico utilizando el método text() de la biblioteca pyplot. Agregaremos el texto "¡Hola, mundo!" en las coordenadas (0, -1).

plt.text(0, -1, r'Hello, world!', fontsize=15)

Agregar título, etiqueta del eje X y etiqueta del eje Y

Podemos agregar un título, una etiqueta del eje X y una etiqueta del eje Y al gráfico utilizando los métodos title(), xlabel() y ylabel() de la biblioteca pyplot. Agregaremos "Voltage vs Time" como título, "Time [s]" como etiqueta del eje X y "Voltage [mV]" como etiqueta del eje Y.

plt.title(r'Voltage vs Time', fontsize=20)
plt.xlabel('Time [s]')
plt.ylabel('Voltage [mV]')

Mostrar el gráfico

Finalmente, mostraremos el gráfico utilizando el método show() de la biblioteca pyplot.

plt.show()

Resumen

En este tutorial, aprendimos cómo crear texto y texto matemático utilizando pyplot. Aprendimos cómo agregar texto al gráfico, cómo agregar título, etiqueta del eje X y etiqueta del eje Y al gráfico, y cómo mostrar el gráfico utilizando pyplot.