Skip to content
Matplotlib

Labels and Legend

Annotate plots with text, arrows, and legend options.

By EZ4Code Team
labelslegendannotation

Code

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)

plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")

plt.title("Trig functions", fontsize=14, pad=12)
plt.xlabel("x")
plt.ylabel("y")

# Text and annotation
plt.text(np.pi, 0, "pi", ha="center", va="bottom")
plt.annotate("max", xy=(0, 1), xytext=(1, 1.2),
             arrowprops=dict(arrowstyle="->"))

# Legend styling
plt.legend(loc="upper right", frameon=True, ncol=2, fontsize=9)
plt.xlim(0, 2 * np.pi)
plt.ylim(-1.2, 1.5)
plt.show()

Explanation

title, xlabel, and ylabel add descriptive text, while text() places arbitrary strings at data coordinates. annotate() draws an arrow from xytext to a target point xy for callouts. The legend can be repositioned and styled, and xlim/ylim set the visible range.

More Matplotlib Snippets