07

Chapter 7 · Python

Python: Matplotlib

Everything hangs off two objects: a Figure, the canvas, and Axes, the plot area inside it. Once that model is clear, every command is either "make these" or "change something on the Axes".

1What Matplotlib is

  1. A plotting library for Python producing static, animated and interactive visualisations.
  2. Created by John Hunter, a neurobiologist working with EEG data, then generalised for wider use.
  3. Its command style has origins in MATLAB, but modern use is object-oriented.
  4. It works directly with NumPy arrays and pandas Series.
How to actually learn it

You cannot remember every command, and you are not expected to. Learn the basic commands well enough to build any standard chart, then know where to look when you need to customise. The gallery in the official documentation is the reference you return to, and copying an example then modifying it is the intended workflow.

The Figure and Axes model

Fig 7.1Hover any part to see what it is and which method sets it
hover a part of the chart

fig is the whole canvas and it is what you save to a file. ax is the region where data is drawn, and almost every customisation is a method on ax. One figure can hold several axes, which is how subplots work in Chapter 8.

The basic workflow

Fig 7.2Seven steps, added one line at a time
lines so far

%matplotlib inline is a Jupyter magic command, and without it plots may open in a separate window. label= on the plot call is what ax.legend() reads, so set it when you draw, not later. Adding a second series is just a second ax.plot(...) call on the same axes.
fig.savefig('my_plot.png')
fig.savefig('report_chart.pdf')     # also .jpg, .svg

savefig is more flexible and scriptable than the notebook's save button, and it is what you use to get a chart into a report or deck.

Colour: six ways to specify it

Fig 7.3Six routes to the same kind of result

What matters is knowing how to access a colour, not memorising palettes. Once you can call a colour by any one of these routes you can build anything, and you look up the exact shade when you need it. The RGBA route is the one that also controls transparency, through its fourth value.

Colormaps

A colormap maps a continuous value onto a colour scale. Use it when colour carries a third variable the axes do not show, for example intensity on a scatter plot or values on a heat map.

Fig 7.4Why viridis is preferred over jet

viridis is perceptually uniform, so equal steps in value look like equal steps in colour. jet is non-uniform, which creates bands that look like features in the data but are not. Custom colormaps come from LinearSegmentedColormap.from_list, and the order you give the colours is the order of the scale, so putting a colour at the start rather than the end reverses which end of the data it marks.

Lines, markers and styles

Fig 7.5Build the plot call and watch the line change
linestyle marker
Only the defined style strings work, and inventing one raises an error. Line style, colour, width and marker shape are all pre-attentive attributes, so this is Chapter 3 applied in code. Distinguish series by shape as well as colour, so the chart survives being printed in greyscale or read by a colour-blind viewer.

Spines

Fig 7.6The four border lines of the plot area
Removing the top and right is the standard decluttering move from Chapter 3. The four spines are 'top', 'bottom', 'left' and 'right', and the methods available are set_visible, set_linewidth and set_color.

The native plot types

Fig 7.7Each type, with the call that draws it

A bar chart needs one categorical variable and one quantitative variable. Switch to 'barh' when category names are long, and rotate tick labels with rot=45 or rot=0 rather than letting long names go diagonal.
df.plot(kind=…)Chartkind=Chart
'line'Line plot'kde'Kernel density estimate
'bar'Vertical bar'scatter'Scatter
'barh'Horizontal bar'pie'Pie
'hist'Histogram'area'Area
'box'Boxplot

The histogram, and what bins does

Fig 7.8One dataset, and the shape you decide to see

bins sets the number of class intervals, which changes the shape you see. It is a judgement, not a default. edgecolor separates adjacent bars so the bins stay readable, and np.random.seed(...) makes a random example reproducible so the chart is the same every run.

Pie chart rules

Fig 7.9Square figsize, explode, and why shadow is banned

Use a square figsize, otherwise the circle is drawn as an ellipse and every angle is distorted. Label order must match value order exactly, or you get a chart that is confidently wrong. explode on one sector is a focal-point device, and skip shadow, because it is a 3D effect and Chapter 3 said those cost and never pay.

Radar or polar chart

Fig 7.10Several quantitative variables radiating from one origin
plt.figure(figsize=(6, 6))
ax = plt.subplot(projection='polar')
ax.plot(theta, r, color='purple', linewidth=3)
  1. Use it to compare several quantitative variables that together describe one phenomenon.
  2. Standard applications are a financial stability map, or target achievement across several product lines in one snapshot.
  3. Area covered reads as overall performance, and plotting two periods together shows whether coverage grew or shrank.
  4. Requires projection='polar' and a square figure.
Switch the second period on and the question changes from "how are we doing" to "which axes did we gain on". Area is being read here, which Chapter 4 ranked fifth of six, so a radar chart ranks well and estimates badly. Label the values when the exact number matters.

Text and annotation

Fig 7.11plt.text against plt.annotate
plt.text(x, y, ...) places text at data coordinates, so the position moves with the axes. plt.annotate adds a pointer, where xy is the point being marked and xytext is where the label sits. arrowprops is what draws the arrow, and without it you get a label with no connector.

Style sheets

Fig 7.12One call changes every aesthetic parameter at once
A style sheet is a pre-built template fixing background colour, grid, line widths and the colour cycle. plt.style.available lists every installed style, including fivethirtyeight and the seaborn-v0_8 family. The style persists: until you call plt.rcdefaults(), every later plot in the session keeps it. This catches people out.

Key points

  1. Figure against Axes, and which one you save.
  2. The standard import block, and what %matplotlib inline does.
  3. np.linspace(start, stop, num).
  4. The seven-step workflow from plt.subplots() to plt.show().
  5. fig.savefig() and the formats it supports.
  6. Six ways to specify a colour, with an example of each.
  7. Why viridis is preferred over jet.
  8. That colour order defines scale direction in a custom colormap.
  9. Line style strings, and that only defined values work.
  10. The four spines, and the three methods for changing them.
  11. plt.hist with bins and edgecolor, and what np.random.seed is for.
  12. The df.plot(kind=…) options.
  13. Why error bars matter when comparing groups.
  14. Pie chart rules: square figure, matching label order, few categories, no shadow.
  15. What explode does and when to use it.
  16. When a radar chart is the right choice.
  17. plt.text against plt.annotate, and the role of arrowprops.
  18. Style sheets, and that you must call plt.rcdefaults() to reset.