MATPLOTLIB:Titles, labels, legends, and saving figures

Mastering titles, labels, legends, and saving figures concepts and implementation.

A chart without labels is a sketch

The title says what comparison the reader is looking at. The axis labels say the units. The legend says which mark is which, and only when there is more than one series.

import matplotlib.pyplot as plt
import pandas as pd

penguins = pd.read_csv("penguins.csv").dropna(
    subset=["bill_length_mm", "bill_depth_mm", "species"]
)

fig, ax = plt.subplots(figsize=(6.5, 4.5))
for species, color in {
    "Adelie": "#f59e0b",
    "Chinstrap": "#7c3aed",
    "Gentoo": "#0ea5e9",
}.items():
    group = penguins.loc[penguins["species"] == species]
    ax.scatter(
        group["bill_length_mm"],
        group["bill_depth_mm"],
        s=16,
        alpha=0.8,
        c=color,
        label=species,
    )

ax.set_title("Bill shape by species")
ax.set_xlabel("Bill length (mm)")
ax.set_ylabel("Bill depth (mm)")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig("bill-shape.png", dpi=140, bbox_inches="tight")

frameon=False drops the box around the legend. dpi=140 is enough for a page. bbox_inches="tight" includes labels that would otherwise be cropped.

Text you should actually write

Prefer a title that states the result or the comparison: "Gentoo penguins are heavier". Prefer axis labels with units: "Body mass (g)", not "body_mass_g". The column name is for the code. The label is for the reader.

ax.set_xlim and ax.set_ylim fix the range when the automatic range hides the story, or when two charts must share a scale. Do not start the y-axis at a misleading value to exaggerate a small gap unless the title says the axis is truncated.

Style without a theme fight

Matplotlib's defaults are readable. You do not need a style sheet for this course. If you do set one, set it before you create the figure:

import matplotlib.pyplot as plt

plt.style.use("seaborn-v0_8-whitegrid")
fig, ax = plt.subplots()

Style names vary by version. If that name raises, print plt.style.available and pick one that exists.

What to notice

  • Add a legend only when a color or a line style encodes a category. A single-series chart with a legend repeats the title.
  • tight_layout() solves most clipped-label problems. Call it after the labels are set.
  • savefig uses the file extension to pick the format. .png for slides and pages, .pdf when a document will be zoomed.

Try this

Rebuild the species scatter, move the legend to "upper right", and save the figure as bills.png.

Next: several panels on one page.