Course page
Log in

You are watching a free preview. Enroll to open all 24 lessons, track progress and ask the course tutor.

Enroll now

Section 1: Principles and first charts

Setting up and the anatomy of a figure

Article 12 min Lesson 2 of 24 Preview

Install the libraries in a project with Jupyter:

uv add pandas matplotlib seaborn plotly jupyterlab
uv run jupyter lab

Two ways to use matplotlib

matplotlib has a quick, state based interface (plt.plot(...)) and an object oriented interface where you work with figure and axes objects directly. The object oriented style is clearer and scales to complex layouts, so we use it throughout:

import matplotlib.pyplot as plt
import pandas as pd

sales = pd.read_csv("data/monthly_sales.csv", parse_dates=["month"])

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(sales["month"], sales["revenue"])
ax.set_title("Monthly revenue")
ax.set_ylabel("Revenue (EUR, thousands)")
plt.show()

The parts of a chart

  • Figure: the whole canvas, which can contain several charts.
  • Axes: one chart area with its own coordinate system. Note the name: an axes object is a whole plot, not a single axis.
  • Axis: the x or y axis, with ticks and labels.
  • Artists: everything drawn, including lines, bars, text and the legend.

Almost every customisation is a method on the axes: ax.set_xlim, ax.set_xticks, ax.legend, ax.annotate, ax.spines.

Cleaning up defaults

A few lines make most charts calmer:

ax.spines[["top", "right"]].set_visible(False)
ax.grid(axis="y", alpha=0.3)
ax.margins(x=0)

Removing the top and right borders, keeping light horizontal gridlines only, and removing padding at the edges of a time series already improves readability.

Formatting numbers

Axis labels like 2500000 are hard to read. Use a formatter:

from matplotlib.ticker import FuncFormatter
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v/1000:.0f}k"))

Saving figures

fig.savefig("revenue.png", dpi=200, bbox_inches="tight")
fig.savefig("revenue.svg", bbox_inches="tight")

PNG at a high resolution works for slides and documents. SVG is a vector format that stays sharp at any size, which is ideal for the web. bbox_inches="tight" trims empty space around the chart.

A style for your project

Instead of repeating settings, set defaults once with plt.rcParams or a style sheet file. We create a small project style with font sizes, colours and gridlines, and apply it at the top of each notebook so every chart looks consistent.

← → switch lessons