runtime
216 / 250
lesson 216 Visualization & EDA · advanced

Figures and axes with matplotlib

A matplotlib chart is a Figure holding one or more Axes. You draw on an Axes with methods such as bar and plot, label it, and can inspect everything you drew.

You'll be able to
  • Create a chart with fig, ax = plt.subplots() and draw on it with ax.bar and ax.plot
  • Give it a title, axis labels and a legend with set_title, set_xlabel, set_ylabel, legend
  • Inspect a chart's bars (ax.patches), lines (ax.get_lines()) and labels, the way a test checks a chart
The idea

A table of monthly revenue is hard to scan; a bar chart shows at a glance which month stood out. matplotlib draws charts in Python. A chart lives in a Figure (the whole image) that holds one or more Axes (one plotting area each, with its own x- and y-axis). fig, ax = plt.subplots() makes one of each. Every drawing call is a method of the Axes: ax.bar(labels, heights) draws bars, ax.plot(x, y) a line. plt.show() displays the figure (here, below the program's output).

Everything you draw becomes an object you can read back: each bar is a rectangle in ax.patches, each line is in ax.get_lines(). That is how this course checks your charts, and how you can test your own.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Revenue per month as bars
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
revenue = [127.31, 55.72, 246.6, 54.55, 17.75, 103.32]   # Runtime Market sample, 2024
fig, ax = plt.subplots()
ax.bar(months, revenue)
ax.set_title("Revenue by month, first half of 2024")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (USD)")
print(len(ax.patches), ax.patches[2].get_height())
print(ax.get_title(), "|", ax.get_ylabel())
print([t.get_text() for t in ax.get_xticklabels()])
plt.show()
example-2.py · Calling the title instead of setting it
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(["Jan", "Feb"], [127.31, 55.72])
ax.title("Revenue")
example-3.py · Highs and lows as two lines
import matplotlib.pyplot as plt

days = ["Jan 1", "Jan 2", "Jan 3", "Jan 4", "Jan 5"]
tmax = [-0.5, 6.7, 9.4, 7.2, 1.7]     # Wichita, NOAA GHCN-Daily
tmin = [-5.5, -4.9, -4.9, -2.1, 0.0]
fig, ax = plt.subplots()
ax.plot(days, tmax, label="high", marker="o")
ax.plot(days, tmin, label="low", marker="o")
ax.set_ylabel("Temperature (C)")
ax.legend()
lines = ax.get_lines()
print([line.get_label() for line in lines])
print([float(v) for v in lines[1].get_ydata()])
print(ax.get_legend() is not None)
plt.show()

When to use it: any chart. Make the Figure and Axes yourself and pass the Axes around, so a function can draw on an Axes it is given or return the Figure it made. Mistakes to avoid: ax.title(...) for ax.set_title(...); unlabeled axes and missing units; lists of labels and values that don't line up; and drawing with plt.* shortcuts inside a function, which draw on whatever chart happens to be current.

Review
  • fig, ax = plt.subplots() makes a Figure with one Axes; draw with ax.bar, ax.plot.
  • Label with set_title, set_xlabel, set_ylabel, and legend() for labelled series.
  • Drawn elements can be read back: ax.patches, ax.get_lines(), ax.get_title().
  • Next: let a DataFrame draw itself onto an Axes.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Figures and axes with matplotlib — Visualization & EDA · Runtime