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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
