Alineación de texto en Matplotlib

Beginner

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

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 se centrará en el alineamiento de texto en 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.

En ocasiones, 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 resolveremos el problema para usted de inmediato.

Creando un rectángulo

Comenzaremos creando un rectángulo en el gráfico utilizando la función Rectangle() del módulo matplotlib.patches. Una vez creado el rectángulo, estableceremos sus límites horizontales y verticales utilizando las funciones set_xlim() y set_ylim(). Finalmente, agregaremos el rectángulo al gráfico.

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, ax = plt.subplots()

## Construye un rectángulo en coordenadas de ejes
left, width =.25,.5
bottom, height =.25,.5
right = left + width
top = bottom + height
p = Rectangle((left, bottom), width, height, fill=False)
ax.add_patch(p)

## Establece los límites horizontal y vertical
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()

Añadiendo texto al rectángulo

En este paso, añadiremos texto al rectángulo utilizando la función text(). La alineación horizontal y vertical del texto se establecerá utilizando los parámetros horizontalalignment y verticalalignment respectivamente.

## Añade texto al rectángulo
ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top),'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.show()

Personalizando el gráfico

En este paso, personalizaremos el gráfico agregando etiquetas de eje y eliminando las líneas de eje.

## Personaliza el gráfico
ax.set_axis_off()
ax.set_xlabel('Etiqueta de X')
ax.set_ylabel('Etiqueta de Y')
ax.set_title('Alineamiento de texto en Matplotlib')
plt.show()

Resumen

En este tutorial, aprendimos cómo alinear texto en Matplotlib. Utilizamos la función text() para agregar texto a un rectángulo y establecimos la alineación horizontal y vertical utilizando los parámetros horizontalalignment y verticalalignment respectivamente. También personalizamos el gráfico agregando etiquetas de eje y eliminando las líneas de eje.