Funciones de texto y anotación a nivel de Figure de Matplotlib


Matplotlib 参考文档Documentación de referencia de Matplotlib

Además de text() y annotate(), Matplotlib también proporciona funciones de texto a nivel de Figure, agregado de tablas y dibujo de flechas.

Lista de funciones

FunciónDescripción
figtext()Agregar texto a nivel de Figure (no en Axes)
figlegend()Agregar leyenda a nivel de Figure (a través de Axes)
table()Agregar tabla en Axes
arrow()Agregar flecha simple

figtext() - Texto a nivel de Figure

matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs)

Similar a text(), pero el sistema de coordenadas es de Figure (0-1), no coordenadas de datos.

Ejemplo

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([0, 1], [0, 1], 'steelblue')
ax.set_title('Axes-level (text vs figtext)')

# Texto a nivel de Axes (coordenadas de datos)
ax.text(0.3, 0.7, 'Axes text (data coords)',
        fontsize=12, color='blue')

# Texto a nivel de Figure (coordenadas relativas de Figure 0-1)
plt.figtext(0.5, 0.02,
            'Figure text at bottom center (Figure coords)',
            ha='center', fontsize=10, color='gray')
plt.figtext(0.02, 0.95,
            'Top left',
            ha='left', va='top',
            fontsize=12, fontweight='bold', color='red')

plt.show()

figlegend() - Leyenda a nivel de Figure

matplotlib.pyplot.figlegend(*args, **kwargs)

Cuando varios Axes necesitan compartir una leyenda, figlegend() puede colocar la leyenda a nivel de Figure.

Ejemplo

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
                                layout='constrained')

# Cada Axes dibuja las mismas dos curvas, pero no agrega leyendas individuales
ax1.plot(x, np.sin(x), 'b-', label='sin(x)')
ax1.plot(x, np.cos(x), 'r--', label='cos(x)')
ax1.set_title('Plot 1')

ax2.plot(x, np.sin(x), 'b-', label='sin(x)')
ax2.plot(x, np.cos(x), 'r--', label='cos(x)')
ax2.set_title('Plot 2')

# Leyenda a nivel de Figure (colocada en la parte superior exterior de la Figure)
fig.legend(loc='outside upper center', ncol=2,
           fontsize=11, frameon=True)

plt.show()

table() - Agregar tabla en Axes

matplotlib.pyplot.table(cellText=None, cellColours=None,
    cellLoc='right', colWidths=None, rowLabels=None,
    rowColours=None, rowLoc='left', colLabels=None,
    colColours=None, colLoc='center', loc='bottom',
    bbox=None, edges='closed', **kwargs)

Ejemplo

import matplotlib.pyplot as plt
import numpy as np

# Datos a mostrar
data = [[85, 90, 78, 92],
        [76, 88, 82, 85],
        [90, 93, 88, 95]]
row_labels = ['Student A', 'Student B', 'Student C']
col_labels = ['Math', 'English', 'Science', 'History']

fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')

# Dibujar gráfico comparativo
x = np.arange(len(col_labels))
for i, (row, label) in enumerate(zip(data, row_labels)):
    ax.plot(x, row, 'o-', label=label, markersize=8)

ax.set_xticks(x)
ax.set_xticklabels(col_labels)
ax.set_title('Student Scores')
ax.legend()
ax.grid(True, alpha=0.3)

# Agregar tabla debajo del gráfico
table = ax.table(cellText=data,
                 rowLabels=row_labels,
                 colLabels=col_labels,
                 cellLoc='center',
                 loc='bottom',
                 bbox=[0, -0.35, 1, 0.25])  # [left, bottom, width, height]

plt.show()

arrow() - Agregar flechas

matplotlib.pyplot.arrow(x, y, dx, dy, **kwargs)

arrow() es un atajo para agregar flechas simples. Para anotaciones con flechas complejas, se recomienda usar annotate().

Ejemplo

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')

# Dibujar el sistema de coordenadas
ax.spines[['left', 'bottom']].set_position(('data', 0))
ax.spines[['top', 'right']].set_visible(False)
ax.set_xlim(-1, 5)
ax.set_ylim(-1, 5)

# Varias flechas
ax.arrow(0, 0, 3, 0, head_width=0.2, head_length=0.2,
         fc='red', ec='red', label='Right 3 units')
ax.arrow(0, 0, 0, 3, head_width=0.2, head_length=0.2,
         fc='blue', ec='blue', label='Up 3 units')
ax.arrow(0, 0, 2, 2, head_width=0.2, head_length=0.2,
         fc='green', ec='green', label='Diagonal')

ax.set_title('arrow() - Simple Arrows')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

Matplotlib 参考文档Documentación de referencia de Matplotlib

Otras extensiones