Section 12.30

Matplotlib

Full name: Matplotlib: a coined name built from MATLAB (matrix laboratory, a commercial numerical computing program whose plotting commands Matplotlib’s first interface imitated), plot and library; it is not an abbreviation.

Definition

Matplotlib is a plotting library for Python §12.23: a program passes it numbers and drawing instructions, and Matplotlib renders a figure on screen or into an image or document file. A figure contains one or more Axes, Matplotlib’s name for a plotting area with its own coordinate system, scales and visible limits. Matplotlib draws exactly what it is told. It does not choose what to measure, check the numbers, or mark data that a scale or a limit leaves out of view. The name is not an abbreviation.

The idea

Readers trust a figure: what it does not show, they assume is not there. Take a service that answered 1,000 requests. 995 took 3 milliseconds each, 3 took 100 milliseconds, and 2 never completed because they hit a timeout §9.34 of 1 second. A plot of the latencies with the vertical range set to 0 to 10 ms shows 995 points in a tidy line. The 3 slow requests lie outside the range and are not drawn. The 2 timed-out requests have no latency value, so they never reached the plotting call at all. The figure is drawn correctly and still tells the reader that every request finished in 3 ms.

The core idea is that plotting is a chain of transformations from numbers to positions, and each link can drop or distort values. A scale maps values to positions. The axis limits keep only a window of positions. A summary such as a box or an error bar §18.1.11 replaces many values by a few. Each link is a decision that the figure’s author should state. A camera is a fair picture: the frame keeps what is inside, and nothing in the photograph shows what was cut off. The picture stops at transformations. A logarithmic scale §18.1.12 does not crop; it stretches small values apart and squeezes large values together.

How it works

  1. Objects. fig, ax = plt.subplots() creates a figure and one Axes; plt is the usual short name for the module matplotlib.pyplot. Every drawn element, such as a line, a set of markers, a bar, an error bar or a text label, is an object that Matplotlib calls an artist.

  2. Data to artists. Calls such as ax.plot(x, y), ax.scatter(x, y), ax.bar(labels, heights), ax.errorbar(x, y, yerr=e) and ax.boxplot(samples) turn arrays §14.5 of numbers into artists. Matplotlib does not know what the numbers mean: yerr draws whatever lengths it is given.

  3. Scale. ax.set_yscale("log") replaces the linear scale of the vertical axis by a logarithmic one. The built-in scales include "linear", "log", "symlog" (linear in a band around zero and logarithmic outside it) and "logit" (for values between 0 and 1).

  4. Limits. By default each axis is scaled automatically to include every finite data value, plus a margin of 5% of the data range on each side. ax.set_ylim(0, 10) fixes the window instead. Lines are cut at the edge of the Axes, and markers outside the window are not drawn; nothing in the figure shows that anything was cut.

  5. Values that cannot be placed. A NaN §4.49 (not a number) or a masked value is skipped, which leaves a gap in a line. On a logarithmic axis, zero and negative values have no position. By default (nonpositive="clip") Matplotlib replaces them by a tiny positive number far below the visible window; with nonpositive="mask" it treats them as missing. Either way the value does not appear in the figure.

  6. Output. fig.savefig("latency.pdf") writes the figure to a file.

Box plots. ax.boxplot draws a box from the first quartile to the third quartile, the values below which 25% and 75% of the data lie, with a line at the median §11.13. By default each whisker reaches the most extreme data value that lies within 1.5 times the interquartile range (the third quartile minus the first) beyond the box. Values beyond the whiskers are drawn as separate points, which Matplotlib calls fliers; the option showfliers=False hides them.

Worked example

A logarithmic axis. On a base-10 logarithmic axis a value yy is placed at height log10y\log_{10} y. The values 1, 10 and 100 map to heights 0, 1 and 2, because 10 to the powers 0, 1 and 2 gives 1, 10 and 100. Equal vertical gaps therefore mean equal ratios: 1 to 10 and 10 to 100 are both tenfold steps. The gap from 100 to 200 is log10200−log10100=log102≈0.301\log_{10} 200 - \log_{10} 100 = \log_{10} 2 \approx 0.301 of a tenfold step, exactly the gap from 1 to 2, although the first difference is 100 and the second is 1.

Clipping and failures. Take the 1,000 requests from above: 995 at 3 ms, 3 at 100 ms, and 2 timed out after 1 s (1,000 ms).

  1. With ax.set_ylim(0, 10), the 995 values at 3 ms are drawn and the 3 values at 100 ms are not, because 100>10100 > 10. The 2 timed-out requests were never passed to Matplotlib. The figure shows 995 of 1,000 requests, and nothing says so.

  2. With a logarithmic axis from 1 to 2,000 ms, 3 ms sits at height log103≈0.477\log_{10} 3 \approx 0.477 and 100 ms at height 2, so both groups are visible in one figure.

  3. A timed-out request has a latency known only to exceed 1,000 ms, a censored observation §11.28. Drawing the 2 timeouts at 1,000 ms with a distinct marker, and writing in the caption “2 requests timed out after 1 s; their latency is unknown and at least 1 s”, shows the failures without inventing values.

A symmetric error bar on a logarithmic axis. The bar 3±2.53 \pm 2.5 ms runs from 0.5 ms to 5.5 ms. On a base-10 logarithmic axis its lower half spans log103−log100.5=log106≈0.778\log_{10} 3 - \log_{10} 0.5 = \log_{10} 6 \approx 0.778 of a tenfold step and its upper half log105.5−log103≈0.263\log_{10} 5.5 - \log_{10} 3 \approx 0.263, so the bar looks lopsided although the interval is symmetric. A bar 3±43 \pm 4 ms would reach −1-1 ms, which a logarithmic axis cannot show at all.

Stated precisely

Let yminy_{\min} and ymaxy_{\max} be the visible limits of the vertical axis and let hh be the height of the Axes. On a linear scale a value yy is drawn at the distance h⋅(y−ymin)/(ymax−ymin)h \cdot (y - y_{\min}) / (y_{\max} - y_{\min}) above the bottom edge. On a base-10 logarithmic scale, which needs y>0y > 0 and ymin>0y_{\min} > 0, the distance is h⋅log10y−log10yminlog10ymax−log10ymin.h \cdot \frac{\log_{10} y - \log_{10} y_{\min}}{\log_{10} y_{\max} - \log_{10} y_{\min}}. Two values with ratio q=y2/y1q = y_2 / y_1 are therefore drawn h⋅log10q/(log10ymax−log10ymin)h \cdot \log_{10} q / (\log_{10} y_{\max} - \log_{10} y_{\min}) apart, whatever their size.

With Matplotlib’s default clipping of artists to the Axes, a data value is visible only if all four conditions hold:

  1. the program passed it to a plotting call;

  2. it is finite;

  3. on a logarithmic axis, it is positive;

  4. it lies within the limits of both axes.

A value that fails any condition is absent, and the figure carries no mark of its absence unless the program adds one. That is the whole contract: Matplotlib shows the values that meet these conditions, at the positions above, and nothing about the others.

Limits and common mistakes

Matplotlib does not choose the estimand §11.2, the quantity a study sets out to estimate, and it does not check that the plotted numbers are right. A correctly drawn figure can display the wrong statistic faithfully.

Error bars and whiskers mean whatever the program computed. A standard deviation §11.14, a standard error §11.15, a 95% confidence interval §11.18 and a min–max range all look alike. Say in the caption which one is drawn and over how many values.

Explicit limits hide data silently. After set_ylim, report how many values fell outside the window and the largest of them, or choose a scale that shows them.

A logarithmic axis cannot show zero or negative values. Replacing 0 by a small positive number such as 0.001 so that it can be drawn changes the data; if a figure does that, its caption must say so. Bars on a logarithmic axis have no natural base, so their lengths depend on where the axis starts and must not be compared as lengths.

The "symlog" scale is linear inside a band around zero whose half-width is a parameter (linthresh) and logarithmic outside it. A reader who does not know where the band ends misreads distances.

Failures that produce no number never reach the plot. Count them separately, report them with the figure, or draw them on purpose as censored values.

Hiding fliers in a box plot, or plotting only means, removes the tail: the rare slow values that decide worst-case behavior, the subject of the tail latency §11.36 entry.

Thousands of points drawn on top of each other look like one dark band. Transparency or a histogram shows how many values each region holds.

Questions answered

Do axis transforms or clipping hide important uncertainty or failures?

Yes, they can, and Matplotlib, the Python plotting library, gives no warning when they do. Matplotlib draws a value only if the program passed it to a plotting call, the value is finite, it is positive when the axis is logarithmic, and it lies inside the axis limits; every other value is simply absent. Concretely:

To prevent this, state the scale, units and limits; report how many values lie outside the limits and the largest of them; count failures and show or report them; say what each error bar is and over how many values; and check that the plotted values are the values the analysis intended.

Related entries: Confidence interval (§11.18), Counter quantization (§11.35), Ratio of aggregates versus aggregate of ratios (§11.40), Censoring (§11.28), Latency distribution and tail (§11.36), Quantile and percentile (§11.16), Binary floating-point representation, special values, and rounding (§4.49). Further reading: [125].