Module 5 · Matplotlib · Lesson 26 of 66

Figures and axes

The object-oriented way: full control over where every chart goes.

In this lesson · about 16 minutes

  • Create a figure and place axes with add_axes
  • Make a grid of charts with plt.subplots
  • Set figure size and save a chart to a file

Matplotlib has a second, more powerful style: create a figure (the blank canvas), add one or more axes (the charts on it), and call methods on those objects. It takes a few more lines but makes multi-chart figures much easier, and it's the style most real code uses.

fig.add_axes([left, bottom, width, height]) places axes using fractions of the figure, from 0 to 1. Notice the methods on axes start with set_: set_xlabel, set_title.

plt.subplots

fig, axes = plt.subplots(nrows=1, ncols=2) makes the figure and a grid of axes in one step. axes is then a NumPy array of charts you can index, axes[0], or loop over. If labels overlap, call fig.tight_layout().

Size, resolution and saving

Pass figsize=(width, height) in inches, and optionally dpi (dots per inch), to plt.figure or plt.subplots. Save a chart with fig.savefig('chart.png', dpi=200). PNG, JPG, SVG and PDF all work, chosen by the file name.

Exercise

Exercise 1: one set of axes

  • Create a figure called fig with plt.figure().
  • Add axes at [0, 0, 1, 1] called ax.
  • Plot x against y and label the axes 'x' and 'y', with the title 'title'.
Code that runs before yours
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y = x * 2
z = x ** 2

Exercise

Exercise 2: two sets of axes

Create a figure with two axes, ax1 at [0, 0, 1, 1] and ax2 at [0.2, 0.5, .2, .2]. Plot x against y on both.

Code that runs before yours
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y = x * 2
z = x ** 2

Exercise

Exercise 3: a zoomed inset

Add axes ax at [0, 0, 1, 1] and ax2 at [0.2, 0.5, .4, .4]. On ax, plot x against z with labels 'X' and 'Z'. On ax2, plot x against y with labels 'X' and 'Y', the title 'zoom', x limits 20 to 22 and y limits 30 to 50.

Code that runs before yours
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y = x * 2
z = x ** 2

Exercise

Exercise 4: side by side

Use plt.subplots(nrows=1, ncols=2, figsize=(12, 2)) to make fig, axes. Plot x against y on the left in blue with line width 3 and a dashed line style, and x against z on the right in red with line width 3.

Code that runs before yours
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y = x * 2
z = x ** 2

Exercises solved: 0 of 4

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.