Direct labels

Annotate a peak.

Annotate a peak.

Goal

Run every block and look at the Plot panel.

df = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr"] * 2,
    "mm": [48, 55, 92, 150, 22, 18, 40, 80],
    "city": ["Nairobi"] * 4 + ["Mombasa"] * 4,
})
nairobi = df[df["city"] == "Nairobi"]
plt.plot(nairobi["month"], nairobi["mm"], marker="o")
plt.annotate("peak", xy=("Apr", 150), xytext=("Mar", 160),
             arrowprops=dict(arrowstyle="->"))
plt.title("Nairobi rainfall")
plt.show()
df = pd.DataFrame({
    "city": ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret"],
    "units": [21, 15, 15, 18, 12],
    "shillings": [2100, 1500, 1480, 1750, 1190],
})
plt.bar(df["city"], df["units"])
for i, v in enumerate(df["units"]):
    plt.text(i, v + 0.3, str(v), ha="center")
plt.title("Direct labels")
plt.show()
df = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr"] * 2,
    "mm": [48, 55, 92, 150, 22, 18, 40, 80],
    "city": ["Nairobi"] * 4 + ["Mombasa"] * 4,
})
for city in ["Nairobi", "Mombasa"]:
    sub = df[df["city"] == city]
    plt.plot(sub["month"], sub["mm"], marker="o", label=city)
plt.legend()
plt.title("Legend when two series")
plt.show()
print("Label the interesting point. Do not label every tick twice.")
Pitfall

Always plt.show(). Paste the whole editor.