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
Objects.
fig, ax = plt.subplots()creates a figure and one Axes;pltis the usual short name for the modulematplotlib.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.Data to artists. Calls such as
ax.plot(x, y),ax.scatter(x, y),ax.bar(labels, heights),ax.errorbar(x, y, yerr=e)andax.boxplot(samples)turn arrays §14.5 of numbers into artists. Matplotlib does not know what the numbers mean:yerrdraws whatever lengths it is given.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).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.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; withnonpositive="mask"it treats them as missing. Either way the value does not appear in the figure.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 is placed at height . 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 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).
With
ax.set_ylim(0, 10), the 995 values at 3 ms are drawn and the 3 values at 100 ms are not, because . The 2 timed-out requests were never passed to Matplotlib. The figure shows 995 of 1,000 requests, and nothing says so.With a logarithmic axis from 1 to 2,000 ms, 3 ms sits at height and 100 ms at height 2, so both groups are visible in one figure.
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 ms runs from 0.5 ms to 5.5 ms. On a base-10 logarithmic axis its lower half spans of a tenfold step and its upper half , so the bar looks lopsided although the interval is symmetric. A bar ms would reach ms, which a logarithmic axis cannot show at all.
Stated precisely
Let and be the visible limits of the vertical axis and let be the height of the Axes. On a linear scale a value is drawn at the distance above the bottom edge. On a base-10 logarithmic scale, which needs and , the distance is Two values with ratio are therefore drawn 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:
the program passed it to a plotting call;
it is finite;
on a logarithmic axis, it is positive;
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:
Explicit axis limits cut off values outside the window, such as rare 100 ms latencies on a 0 to 10 ms axis.
A logarithmic axis cannot place zero or negative values; it drops them or pushes them out of view. It also makes a symmetric error bar look lopsided, and it cannot draw an error bar whose lower end is at or below zero.
Failed attempts, such as requests that timed out, have no value and never appear unless the program plots them on purpose.
Box plots with the outlying points (fliers) hidden, or bars that show only means, remove the tail of the data.
An error bar can be a standard deviation, a confidence interval or a min–max range; unlabeled, the reader cannot tell how much uncertainty it shows.
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].