Plotting Arrays

Arrays often need inspection before computation continues.

A one-dimensional array can become a line plot or histogram. A two-dimensional array can be inspected as an image-like grid.

plt.imshow(matrix)

This does not mean the data is a photograph. It means values are shown by color.

Inspect a matrix

Plot a small matrix

Runs locally with Python in your browser.

Ready to run.

The colorbar gives a scale for the colors. Without it, the colors are harder to interpret.

Matplotlib normally chooses the color limits from each displayed array. That is convenient for inspecting one matrix, but it can mislead when comparing two figures: the same color may represent different values. Use shared limits when the colors must be comparable:

plt.imshow(A, vmin=0, vmax=10)

Plot rows or columns

Sometimes a matrix is better inspected by plotting rows:

This is useful when each row is a short sequence.

Always state what axes mean

For imshow, the visual axes are still array axes:

vertical position -> row index
horizontal position -> column index

If the rows are examples and columns are features, say so in the title or surrounding text.

Exercise: Matrix plot

Which Matplotlib function displays a two-dimensional array as a color grid?

Answer it first, then check.

Hint

The function name begins with “im” and means “show an image.”

Solution

Use imshow, usually as plt.imshow(A). It maps the values in a two-dimensional array to colors in a grid.