1What Matplotlib is
- A plotting library for Python producing static, animated and interactive visualisations.
- Created by John Hunter, a neurobiologist working with EEG data, then generalised for wider use.
- Its command style has origins in MATLAB, but modern use is object-oriented.
- It works directly with NumPy arrays and pandas Series.
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 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
%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
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.
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
Spines
'top', 'bottom', 'left' and 'right', and the methods available are set_visible, set_linewidth and set_color.The native plot types
'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=…) | Chart | kind= | 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
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
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
plt.figure(figsize=(6, 6))
ax = plt.subplot(projection='polar')
ax.plot(theta, r, color='purple', linewidth=3)
- Use it to compare several quantitative variables that together describe one phenomenon.
- Standard applications are a financial stability map, or target achievement across several product lines in one snapshot.
- Area covered reads as overall performance, and plotting two periods together shows whether coverage grew or shrank.
- Requires
projection='polar'and a square figure.
Text and annotation
plt.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
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
- Figure against Axes, and which one you save.
- The standard import block, and what
%matplotlib inlinedoes. np.linspace(start, stop, num).- The seven-step workflow from
plt.subplots()toplt.show(). fig.savefig()and the formats it supports.- Six ways to specify a colour, with an example of each.
- Why
viridisis preferred overjet. - That colour order defines scale direction in a custom colormap.
- Line style strings, and that only defined values work.
- The four spines, and the three methods for changing them.
plt.histwithbinsandedgecolor, and whatnp.random.seedis for.- The
df.plot(kind=…)options. - Why error bars matter when comparing groups.
- Pie chart rules: square figure, matching label order, few categories, no shadow.
- What
explodedoes and when to use it. - When a radar chart is the right choice.
plt.textagainstplt.annotate, and the role ofarrowprops.- Style sheets, and that you must call
plt.rcdefaults()to reset.