Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

0.5 Visualization with Matplotlib

A plot can reveal structure that is difficult to see in a table. A useful plot has a clear purpose, labeled axes, readable scales, and enough context to interpret it.

Line plots

Use a line plot when horizontal position represents an ordered quantity and connecting adjacent points is meaningful.

<Figure size 640x480 with 1 Axes>

The fig, ax = plt.subplots() pattern gives explicit control over the figure and its axes. Prefer it over relying on hidden plotting state.

Scatter plots

Use a scatter plot to examine the relationship between two measured variables.

<Figure size 640x480 with 1 Axes>

The plot suggests a positive association, but the plot alone does not establish causation.

Plotting vectors in the plane

A two-dimensional vector can be drawn as an arrow from the origin.

<Figure size 640x480 with 1 Axes>

Setting equal aspect ratio is important: one unit in the horizontal direction should occupy the same visual distance as one unit vertically.

Multiple panels

Subplots make comparisons easier when panels share a structure.

<Figure size 900x350 with 2 Axes>

A plotting checklist

Before accepting a figure, ask:

Practice

Exercise 1: plot two functions

On one set of axes, plot y=xy=x and y=x2y=x^2 for −2≤x≤2-2\leq x\leq2. Add labels and a legend.

Solution
<Figure size 640x480 with 1 Axes>

Exercise 2: visualize vector addition

Let u=(2,1)u=(2,1) and v=(1,2)v=(1,2). Draw uu, vv, and u+vu+v from the origin. Use three distinguishable colors and an equal aspect ratio.

Solution
<Figure size 640x480 with 1 Axes>