Python / Data Science Essentials Interview Questions
How do you add annotations and text to Matplotlib charts?
Annotations turn a chart into a story — highlighting a key data point, marking a threshold, or labelling significant events on a timeline. Matplotlib provides ax.annotate() for arrow-and-text annotations and ax.text() for free-form text placement.
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 200) y = np.sin(x) * np.exp(-x / 5) fig, ax = plt.subplots(figsize=(9, 5)) ax.plot(x, y, color='steelblue', linewidth=2) # Find and annotate the maximum peak_idx = np.argmax(y) px, py = x[peak_idx], y[peak_idx] ax.annotate( f'Peak: ({px:.2f}, {py:.2f})', xy=(px, py), # point to annotate xytext=(px + 1.5, py), # where the text goes arrowprops=dict( arrowstyle='->', color='darkred', lw=1.5, ), fontsize=11, color='darkred', ) # Free-form text label ax.text(0.5, 0.9, 'Damped oscillation', transform=ax.transAxes, # axes-relative coords (0â1) fontsize=12, ha='center', bbox=dict(boxstyle='round,pad=0.3', fc='lightyellow', ec='grey')) # Threshold line with label ax.axhline(y=0.5, color='orange', linestyle='--', linewidth=1) ax.text(9.5, 0.52, 'threshold=0.5', color='orange', ha='right', fontsize=9) ax.set(title='Annotated Damped Sine', xlabel='x', ylabel='y') ax.spines[['top', 'right']].set_visible(False) plt.tight_layout(); plt.show()
The two coordinate systems matter: xy in annotate uses data coordinates by default (values from your actual data range). Passing transform=ax.transAxes to ax.text() switches to axes-fraction coordinates (0,0 = bottom-left, 1,1 = top-right) — useful for fixed-position labels that stay put when the data range changes.
More Related questions...