You trained a small network for 40 epochs and your code printed 40 numbers for the training loss and 40 for the validation loss. Somewhere in those 80 numbers is the answer to the question “should I stop training?”, but nobody can read it from the list. Draw them as two lines, and in one second you see the training loss still falling while the validation loss turned up around epoch 22. A plot is the fastest way to find out what your numbers are doing.
Matplotlib is the standard Python library for drawing such plots. Almost every ML tutorial, paper notebook and library plots with it, or with a tool built on it (pandas plotting in P2.5, and seaborn, a library that draws statistical plots on top of Matplotlib). This lesson teaches the small part of it that you use constantly, and the habits that keep the pictures honest.
On this page you can run real Matplotlib in your browser. Each runnable plot below already shows its picture, so you can read the whole lesson without running anything. If you press Run, the first run downloads about 19 MB (the box tells you before it starts) and then every plot on the page draws quickly.
Two objects: Figure and Axes
Start with the picture in your head. A Figure is the whole sheet of paper (or the whole image file). An Axes is one plot drawn on that sheet: the rectangle with the data, the ticks, the labels and the title. One Figure can hold one Axes or many. The x-axis and the y-axis, the two lines with their numbers, are each an Axis. The word is easy to confuse with Axes, so read the plural carefully. The things you draw are called artists: lines, dots, bars, text.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 50)
fig, ax = plt.subplots() # a new Figure with one Axes
ax.plot(x, np.sin(x)) # draw on that Axes
ax.set_title("sin") # decorate that Axes
plt.subplots() returns two things: the Figure fig and the Axes ax. Everything you draw or label is a method call on ax (ax.plot, ax.set_xlabel, ax.set_title), and things about the whole picture are methods on fig (fig.savefig, fig.colorbar, fig.suptitle).
There is a second style, which you will see in many tutorials. The pyplot functions (plt.plot, plt.title) draw on a hidden “current Axes”, which they create for you if needed:
plt.plot(x, np.sin(x)) # draws on the current Axes (made automatically)
plt.title("sin") # titles the current Axes
Both give the same picture. The first style is called the object-oriented (or explicit) style, the second the pyplot (or implicit) style. This lesson uses the first, and you should too, for three reasons.
- You always know where a drawing goes. With several plots,
plt.title("A")goes to whichever Axes happens to be current, which is the last one you touched. Callingax2.set_title("A")has only one meaning. - It scales. Grids of plots, a function that draws on an Axes you pass in, and two figures open at once all work without surprises. The Matplotlib documentation describes both styles and lists the trade-offs; the explicit one is what it recommends for anything beyond a quick look.
- The names are the same everywhere.
plt.xlabelbecomesax.set_xlabel,plt.xlimbecomesax.set_xlim,plt.legendstaysax.legend: addset_when the pyplot function sets a property.
Pyplot is not wrong. It is the shortest way to draw one quick plot in a notebook. A good rule: pyplot to create the figure, methods on fig and ax for everything else (that is exactly what plt.subplots does). Mixing the two styles is the source of many “my title went to the wrong plot” mistakes.
Line plots: the loss curve
A line plot connects points (x[0], y[0]), (x[1], y[1]), ... in order. It suits a quantity that changes along an ordered x, such as a loss per epoch, a learning rate per step or a function of time. In ML you draw it more than any other plot.
ax.plot(x, y) # x and y: arrays of the same length
ax.plot(y) # only y: x becomes 0, 1, 2, ...
ax.plot(x, y, color="#0072B2", linestyle="--", linewidth=2, marker="o", label="train")
The useful options are color, linestyle ("-", "--", ":"), linewidth, marker ("o" circle, "^" triangle, "s" square) and label. Each call to ax.plot adds one more line to the same Axes, and ax.legend() shows the labels you gave. The usual way to get a training curve is to record the loss in a list while the loop runs, and to plot the list afterwards:
losses = []
for step in range(30):
loss = ... # your training step goes here
losses.append(loss) # remember it
fig, ax = plt.subplots()
ax.plot(losses) # x is the step number 0, 1, 2, ...
ax.set_xlabel("step")
ax.set_ylabel("loss")
Now the first live plot. It draws a made-up 40-epoch run with the training loss falling steadily while the validation loss turns up (overfitting, P3.A3). It also uses a log scale on the y-axis.
Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Three things in that code deserve a word.
Log scale, ax.set_yscale("log"). A loss often starts near 2 and ends near 0.02: a factor of 100. On a linear axis, everything below 0.2 is squeezed into the bottom tenth of the picture and you cannot see whether the training loss is still improving. On a log axis, equal ratios get equal vertical distance, so falling from 2 to 0.2 takes the same height as falling from 0.2 to 0.02, and a curve that decays like becomes a straight line. A log axis cannot show zero or negative values (the logarithm is undefined there), so it suits a loss, which is positive. Remove the set_yscale line in the runner and compare. (Use set_xscale("log") for an x such as a learning rate that you vary over several powers of ten.)
Reading the picture. If both curves fall together, the model is still learning. If the training loss falls and the validation loss turns up, the model is memorizing the training data: that is overfitting, and the epoch where the validation loss is lowest is where you would have stopped (P4.22 teaches a whole gallery of such shapes). Plotting the validation loss as well as the training loss is what makes this visible. The two losses are measured on different data: the training set and a held-out validation set (P3.A4).
figsize and tight_layout. figsize=(4.5, 3) is the width and height of the Figure in inches. The default is (6.4, 4.8) and the default resolution is 100 dots per inch, so the default picture is 640 by 480 pixels. fig.tight_layout() adjusts the spacing so that labels do not overlap or get cut off.
Scatter plots: two features, coloured by class
A scatter plot draws one dot per example at its two feature values. It shows clusters, trends and outliers, and it is the basic picture of a classification problem (P1.D7 used it to show what a correlation hides).
ax.scatter(x, y) # one dot per (x[i], y[i])
ax.scatter(x, y, s=20, alpha=0.6, color="#0072B2", marker="o", label="class 0")
sis the marker area in points squared (a point is 1/72 inch), so doubling the width of a dot means multiplyingsby 4. The default is 36.alphais opacity from 0 (invisible) to 1. When many dots land on top of each other (overplotting), the blob looks like one solid shape and hides how dense it is. Small dots (s=5tos=20) andalphaaround 0.2 to 0.6 let you see density, because overlapping dots then look darker.- To colour by class, draw one
scattercall per class, using a Boolean mask to pick the rows, and give each alabel. IfXhas shape(n, 2)andyholds the class labels with shape(n,):
for k, name in enumerate(["class 0", "class 1"]):
ax.scatter(X[y == k, 0], X[y == k, 1], label=name)
The other way is ax.scatter(X[:, 0], X[:, 1], c=y), which colours each dot by its label through a colour map; then handles, names = sc.legend_elements() (where sc is the object scatter returned) gives you legend entries. The loop is simpler to read and lets you change the marker per class.
Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

A scatter plot is also the quickest look at a classification problem: if one straight line could separate the two colours, a linear classifier such as logistic regression (P3.A7) would do well; if the colours mix as they do here, even the best line makes some mistakes, and you may want more features or a model that can bend, such as a neural network (Part 4).
Histograms: how bins change the story
A histogram shows how the values of one variable are spread out. Matplotlib cuts the range into bins, counts how many values fall in each, and draws one bar per bin.
ax.hist(x, bins=10) # 10 equal-width bins between min(x) and max(x) (the default is also 10)
ax.hist(x, bins=16, range=(0, 80)) # fix the range, so several histograms share the same bins
ax.hist(x, bins=[0, 20, 40, 80]) # or give the bin edges yourself (unequal widths allowed)
ax.hist(x, bins=8, density=True) # heights become a probability density
ax.hist also returns the counts and the bin edges, and np.histogram(x, bins=8, range=(0, 80)) computes the same numbers without drawing. A value exactly on an edge goes into the bin on its right, except that the very last bin also includes its right edge (so a value of 80 counts in the last bin of range=(0, 80)).
The number of bins changes the story. Here are the same 60 made-up values as in the statistics lesson (P1.D12), drawn with 4, 16 and 80 bins. With 4 bins (each 20 wide) the bars read 8, 20, 29 and 3 and look like one hill. With 16 bins (each 5 wide) the picture shows two clear groups, one between about 10 and 30 and one between about 40 and 70, with an empty stretch from 30 to 40. With 80 bins (each 1 wide) the values break into thin bars: 31 of the 80 bins hold anything (1 to 5 values each), and the shape is lost in noise. Nothing in the data changed.
Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

There is no single right bin count. Try several, be suspicious of a feature that appears at only one of them, and when you compare two histograms use the same range and the same number of bins. Matplotlib also accepts rules such as bins="auto", which picks a count from the data (it gives 7 bins here), but a rule is a starting point, not an answer.
density=True. By default the bar height is a count. With density=True the height is the count divided by (total count times bin width), so that the area of all the bars adds up to 1. It is not that the heights add to 1. For the 8 bins of width 10 above, the bin from 20 to 30 holds 20 of the 60 values, so its height is , and the eight areas add up to exactly 1. Use density=True when you overlay two groups of different sizes (say 900 cats and 100 dogs): counts make the small group vanish, densities compare their shapes. Remember that a density can exceed 1 for a narrow bin; it is not a probability.
Bar chart or histogram? ax.bar(names, heights) draws a bar of the height you give for each category, and does no counting. ax.hist(values) takes the raw values, bins them and counts. A bar chart shows a number per category (the accuracy of three models, the number of images per class); use a histogram for a continuous quantity.
Honest axes: bars start at zero
A bar encodes its value by its length, so the bar must start at zero. If the axis starts at 0.90, a bar for 0.93 is three times as long as a bar for 0.91, but the models differ by two percentage points. Lines and dots encode by position, so an axis that does not start at zero is acceptable for them (a loss curve does not need the zero), but for bars it is a distortion.
Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Two more honesty habits. Compare on one scale: when two plots are meant to be compared, give them the same axis limits (sharey=True, or the same set_ylim), the same bins and, for images, the same vmin and vmax. Otherwise each plot stretches to fill its own box and a small thing can look as big as a large one. Say what the numbers are: label axes with the quantity and its unit, and write “made up” or the data source in the title or caption.
Images and matrices: imshow
ax.imshow(A) draws a 2-D array as a grid of coloured squares: one square per entry. That one function covers three jobs.
- A grey-scale image. An array of shape
(height, width), for instance a 28 by 28 digit. Row 0 is drawn at the top, like the rows of a matrix and of an image file. - A colour image. An array of shape
(height, width, 3)(red, green, blue), with floats between 0 and 1 or integers between 0 and 255. Shape(height, width, 4)adds opacity. Other shapes such as(height, width, 2)give an error. (Images as tensors are the subject of P5.1.) - Any matrix as a heat map. A confusion matrix, an attention matrix, a correlation matrix, a weight matrix: the colour shows the size of each entry.
The settings that matter:
cmapis the colour map, the rule that turns a number into a colour. For a 2-D array the default is viridis, so a grey-scale photograph shows up in purple, green and yellow unless you saycmap="gray". A 3-D colour image ignorescmap.vminandvmaxset which numbers get the lowest and the highest colour. By default they are the smallest and largest value of this array, so two images drawn with the defaults are not on a shared scale. Set them explicitly (vmin=0, vmax=255, or onevminandvmaxfor both images) when you compare.fig.colorbar(im, ax=ax)adds the key from colours to numbers. Hereimis whatimshowreturned. A heat map without a colour bar is decoration.originis"upper"by default: entry[0, 0]is the top-left square.origin="lower"puts it at the bottom-left, which suits a plot of a function over a grid where y grows upward.aspectdefaults to"equal": squares stay squares. Useaspect="auto"for a very wide or tall matrix.interpolationis how Matplotlib fills the space between squares when it resizes. With the default ("auto"), a small array drawn large gives sharp squares (what you want for a 5 by 5 array). Writeinterpolation="nearest"to make that certain.
Which colour map? Use viridis (the default sequential map) or another perceptually uniform one: equal steps in the number look like equal steps in colour, the map still reads in grey scale when printed, and it was designed to stay readable for the common forms of colour blindness. Avoid rainbow maps such as jet: they show bands and edges that are not in the data, and their lightness does not rise steadily with the value. For signed numbers (a gradient, a weight change, a correlation) use a diverging map such as "RdBu" with vmin=-m, vmax=m for one symmetric limit m, so that zero is the middle colour.
The next runner draws both jobs next to each other: a tiny 5 by 5 grey-scale image, and a confusion matrix with a colour bar and the counts written in the squares. A confusion matrix has one row per true class and one column per predicted class; the entry in row , column counts the examples of class that the classifier called . A perfect classifier has numbers only on the diagonal (P3.A9 explains the metrics built from it). These counts are made up: 150 images and 133 correct, so the accuracy is .
Optional: runs real Matplotlib in your browser. The first run downloads about 19 MB (Python 6 MB, then Matplotlib with NumPy 13 MB), once; your browser keeps it (less if you already ran another Python cell on this site). The picture below is what the code draws.

Notice the line that picks the text colour: white on the dark squares and black on the bright ones, so every number stays readable. In the same way, ax.text(x, y, "words") writes at a data position and ax.annotate adds an arrow.
Grids of plots: subplots
plt.subplots(rows, cols) makes a Figure with a grid of Axes and returns the Figure and the Axes:
fig, axes = plt.subplots(2, 3, figsize=(9, 5)) # 2 rows, 3 columns, 6 Axes
axes[0, 1].plot(...) # row 0, column 1
for ax in axes.flat: # visit all six one after another
ax.set_xlabel("epoch")
What axes is depends on the grid, which is a classic stumbling block:
| Grid | axes is | Pick one Axes |
|---|---|---|
plt.subplots() (1 by 1) | a single Axes, not an array | use it directly |
plt.subplots(1, 3) or plt.subplots(3, 1) | a 1-D array of 3 | axes[2] |
plt.subplots(2, 3) | a 2-D array of shape (2, 3) | axes[1, 2] |
Unpacking is only convenient when you know the grid: fig, (ax1, ax2) = plt.subplots(1, 2). To treat all cases the same, pass squeeze=False (you always get a 2-D array) and use axes.flat. Other settings you will use:
sharex=True,sharey=Truegive all plots one x-axis or y-axis scale, and show the tick labels only on the outer plots. Use them whenever the panels are to be compared (the histogram runner above does).figsize=(width, height)is in inches for the whole Figure. A phone-friendly picture is narrow, such as(4.5, 3).fig.tight_layout()(or the settinglayout="constrained"inplt.subplots, a newer and often better layout engine) stops titles and labels from overlapping.fig.suptitle("...")puts one title over the whole Figure. A grid is also the usual way to plot one training curve per metric (loss, accuracy) or one image per class.
Labels, legends, limits and ticks
Every plot you show someone needs the same few lines. A plot without them is a puzzle.
ax.set_xlabel("epoch") # what the x-axis is (add units: "time (s)")
ax.set_ylabel("loss") # what the y-axis is
ax.set_title("Training loss") # what the whole plot is
ax.legend() # needed when there are two or more labelled series
ax.set_xlim(0, 40) # axis range (also ax.set_ylim(low, high))
ax.set_yscale("log") # or "linear"
ax.grid(True, alpha=0.3) # faint grid lines, easier to read values
ax.axhline(0.5, color="gray", linestyle=":") # a horizontal reference line (axvline for vertical)
ax.set(xlabel="epoch", ylabel="loss") # several setters in one call
ax.legend() only lists artists that have a label. If you forget the label= in the plot call, you get a warning and an empty legend. Matplotlib puts the legend where it overlaps least; loc="upper right" places it by hand.
Saving a figure
fig.savefig("loss.png", dpi=150, bbox_inches="tight") # raster image for slides, web and reports
fig.savefig("loss.pdf") # vector, for a paper: sharp at any zoom
fig.savefig("loss.svg") # vector, for the web
plt.close(fig) # free the memory when you are done with it
The file type comes from the extension. The picture is figsize times dpi pixels: figsize=(4.5, 3) with dpi=150 is a 675 by 450 pixel PNG. bbox_inches="tight" trims the white margin and makes sure that no label is cut off, which changes the final size slightly. Use transparent=True for a transparent background (take care: black text on a transparent picture disappears on a dark page). Vector formats (PDF, SVG) store the shapes and stay sharp at any size, and are the better choice for papers. Raster formats (PNG) store pixels and are good for photographs and very busy plots.
Save before plt.show() in a script: after you close the window the figure may be gone, and a later savefig can write an empty picture. In a loop that makes many figures, call plt.close(fig) after saving each one: Matplotlib keeps every open figure in memory and warns after 20.
Notebook, script or server: where does the plot appear?
- In a notebook (Jupyter, Colab): the figure appears under the cell by itself. Use
plt.show()at the end if you want to be explicit. - In a plain script run from the command line: nothing appears until you call
plt.show(), which opens a window and waits until you close it. Forgetting it is the most common “my script plots nothing” problem. - On a server without a screen: use
fig.savefig("name.png")and open the file. Matplotlib then needs a backend that draws into memory, called Agg. - On this page, the runners use Agg and show the result under the code, so
plt.show()does nothing here (it is safe to leave it in). The runner shows the current figure (plt.gcf()), the last one you created. It also setsfigure.dpito 110 and the font size to 12 before your code runs, so that text stays readable when the picture shrinks to a phone screen.
Common mistakes
- Missing labels and units. The plot makes sense to you, today. Add
set_xlabel,set_ylabel, a title and a legend. - Wrong array shape.
ax.plot(x, y)wantsxandyto have the same length. A column of shape(n, 1)works (it is one line), and a 2-D array of shape(n, 3)draws three lines, one per column. But a row of shape(1, n)is read asnlines of one point each, which draw nothing you can see, andax.plot(x, y_row)raises an error about the first dimension. Checky.shape, and flatten withy.ravel(). The same shape trap breaks masks: with labels of shape(n, 1), the masky == kis 2-D andX[y == k, 0]fails, so usey.ravel()first. plt.titleafter several Axes. It titles the current Axes, not the one you meant. Useax.set_title.- Unsorted x in a line plot.
plotjoins the points in the order you give them, so unsorted x gives a zigzag. Sort first (np.argsort) or usescatter. - NaN values. A
naninyleaves a gap in the line. That is usually what you want, and surprising if you did not know. A loss that turnednanshows up as a line that stops. - A grey-scale image in the wrong colours.
ax.imshow(img)for a 2-D array uses viridis. Passcmap="gray". - A forgotten
plt.show()in a script, orsavefigaftershow(see “Saving a figure”). - Many figures left open in a loop (see “Saving a figure”).
- Colour as the only signal, and truncated or different axes (see “Honest axes”).
What Matplotlib is not
Matplotlib is low-level: you say every detail. Other tools build on it or replace it: pandas draws a plot from a table with one call, df.plot() (P2.5), seaborn draws statistical plots such as grouped histograms and heat maps with better defaults, and Plotly draws interactive plots in a browser. They are out of scope here. Training tools that live in a browser tab (TensorBoard, or the dashboards of experiment trackers, P12.3) show the same loss curves while a model trains. The objects from this lesson, a Figure with Axes, are what you meet whenever any of these tools hands you a plot to adjust.
Intuition
A Figure is a sheet of paper, and each Axes is a framed picture glued onto it. plt.subplots(2, 3) buys a sheet with six empty frames. You do not paint on the sheet: you paint inside a frame (ax.plot), and write on the frame’s border (ax.set_xlabel). A log axis is a ruler where every step is “times ten” instead of “plus ten”. A histogram is a row of buckets: you choose how wide each bucket is, and the picture is how many values fell into each one. The analogy breaks at the pyplot shortcuts: there Matplotlib guesses which frame you meant, and it guesses the last one you touched.
Math
Log axis. A loss that decays as has , a straight line in with slope . On a log axis the vertical position of a value is proportional to , so a ratio always takes the same distance, wherever it occurs. That is why a straight line on a log axis means exponential decay, and why a curve that flattens out on it means the decay is slowing.
Histogram density. For values and bin with count and width , density=True draws the height
so the area of bar is , the share of the data in that bin, and the areas add up to . For the data above with 8 bins of width 10 the heights are 0, 0.0133, 0.0333, 0, 0.0183, 0.03, 0.005 and 0.
Image size. A figure of figsize=(W, H) inches saved at dots per inch has by pixels: and .
Code
A reusable recipe: a function that draws on an Axes you pass in, so you can place it in any grid.
import numpy as np
import matplotlib.pyplot as plt
def plot_curves(ax, history, title):
"""history: dict of name -> list of numbers. Draws on the Axes you give it."""
for name, values in history.items():
ax.plot(values, label=name)
ax.set_title(title)
ax.set_xlabel("epoch")
ax.legend()
history = {"train": [1.0, 0.5, 0.3, 0.2], "val": [1.1, 0.7, 0.5, 0.5]}
fig, axes = plt.subplots(1, 2, figsize=(7, 3))
plot_curves(axes[0], history, "linear")
plot_curves(axes[1], history, "log")
axes[1].set_yscale("log")
fig.tight_layout()
fig.savefig("curves.png", dpi=150, bbox_inches="tight")Pass the Axes in and the function works for a single plot or for a cell in a grid. The same shape (ax as the first argument) is what libraries such as pandas and seaborn use.
Go deeper Two y-axes, and why to be careful
ax2 = ax.twinx() makes a second Axes that shares the x-axis and has its own y-axis on the right, so one plot can show a loss (left) and an accuracy (right). It is handy and easy to abuse: the two scales are unrelated, so you can make two lines cross anywhere by choosing the limits. When you can, draw two panels with sharex=True instead, and if you use twinx, colour each y-axis label like its line.
Go deeper Colour normalization: LogNorm and TwoSlopeNorm
vmin and vmax map numbers to colours linearly. A norm changes that rule. matplotlib.colors.LogNorm() spaces colours by the logarithm, useful for a matrix with values from 0.001 to 1000 (it needs positive values). TwoSlopeNorm(vcenter=0) (from matplotlib.colors) puts a chosen number, such as zero, at the middle of a diverging map even when the data range is not symmetric. You pass one to imshow as norm=... instead of vmin and vmax. Both change what the colours mean, so keep the colour bar and say so.
Go deeper Backends, the pyplot state machine and layouts
A backend is the part of Matplotlib that turns a Figure into something you see or save. Window backends (such as Qt or Tk) show an interactive window, notebook backends show the figure in the cell, and Agg draws into memory, which suits a program with no screen and is what the runners on this page use. Pyplot keeps a global list of open figures and a “current” one and Axes inside it; plt.gcf() and plt.gca() return them. That global state is what makes plt.plot work without a variable, and why it misbehaves when you juggle several plots.
For layouts, plt.subplot_mosaic([["a", "b"], ["c", "c"]]) makes a grid where one plot spans two cells and returns the Axes by name, and layout="constrained" places colour bars and labels without overlaps more reliably than tight_layout.
Try it
The five runnable plots above are the activity of this lesson: run each one, then change one thing and run it again. Here are some changes to try, one for each plot.
- Loss curves. Delete the
ax.set_yscale("log")line. Which of the two curves becomes hard to read? Change the0.012 * epochsterm invalto0.005 * epochs: where does the best epoch move? - Scatter. Set
alpha=1ands=60. What can you no longer see? Then move class 1’s mean from[3.2, 3.0]to[5.0, 5.0]: how do the clouds change? - Histogram. Edit
bins_to_tryto[8, 10, 12]. Does the gap between the two groups appear at all three? Then adddensity=Trueto theax.histcall and read the new y-axis. - Bars. Change
ax1.set_ylim(0.90, 0.94)toax1.set_ylim(0.909, 0.931). How many times taller does model B look now? - imshow. Change
cmap="viridis"tocmap="jet". Do the bright and dark bands match the sizes of the numbers? Then changecmap="gray"for the image tocmap="viridis".
Check your understanding
What does
fig, ax = plt.subplots()return?With no arguments,
plt.subplots()makes a one-by-one grid and returns the Figure and a single Axes object, not an array. The x-axis and y-axis (Axis objects) belong to an Axes. The legend is part of an Axes, not an extra Axes. A 1-D or 2-D array of Axes appears only for grids with more than one plot.You call
fig, axes = plt.subplots(1, 4). How do you draw on plot number 3, counting from 1?A grid with one row gives a 1-D array of four Axes, and counting starts at 0, so plot number 3 has index 2. Two indices fail because the array has only one dimension. Index 3 would be plot number 4. The array itself has no
plotmethod.A training loss falls from 2.0 to 0.002 over 100 epochs. Why is
ax.set_yscale("log")a good choice?On a log axis a fall by a factor of ten takes the same height wherever it happens, so 2.0 to 0.2 and 0.02 to 0.002 look alike. On a linear axis everything under 0.2 would be squashed into the bottom tenth. A scale changes only how values are drawn, not their size, and not their order. Matplotlib draws numbers below 1 on a linear axis without trouble.
You draw
ax.hist(x, bins=8, range=(0, 80), density=True)for 60 values, and 8 of them fall in the bin from 10 to 20. What is the height of that bar?With
density=Truethe height is the count divided by the total count times the bin width, so that the areas add up to 1: and the bar area is , the share of the data. The raw count 8 is the height withoutdensity. The value 0.133 is that share, which is the area and not the height. Dividing by the width alone ignores the total.A bar chart shows accuracy 0.91 for model A and 0.93 for model B on a y-axis that runs from 0.90 to 0.94, and B's bar is three times as tall as A's. What is wrong?
A bar encodes its number by its length from the baseline, so the baseline has to be zero. Starting at 0.90 makes 0.93 look three times as long as 0.91 although the two numbers are close. Red and green are a poor pair for colour-blind readers and add no information. A histogram counts values in bins, which is not what one number per model is.
You draw a 28 by 28 grey-scale digit with
ax.imshow(img)and see a purple and yellow picture. What is the likely reason and the fix?For a 2-D array
imshowmaps numbers to colours with a colour map, and the default is viridis, which runs from purple to yellow.cmap="gray"shows the values as grey. The array already has a fine shape for a grey image.imshowis exactly the function for images, andplt.show()only displays the figure, it does not change colours.
Exercises
- Write the lines that draw for 50 points of between and in the Figure-and-Axes style, with labels for both axes and a title.
Show answer
x = np.linspace(-3, 3, 50), thenfig, ax = plt.subplots(),ax.plot(x, x**2),ax.set_xlabel("x"),ax.set_ylabel("y = x squared")andax.set_title("A parabola"). Every drawing and label is a method onax. x = np.arange(5)andy = np.array([[1, 2, 3, 4, 5]])(shape(1, 5)). What doax.plot(y)andax.plot(x, y)do, and how do you fix them?Show answer
ax.plot(y)reads the array as 5 columns, so it draws 5 lines of one point each, which are invisible with the default style.ax.plot(x, y)raises aValueErrorbecausexhas shape(5,)andyhas shape(1, 5). Usey.ravel()(shape(5,)) ory[0], thenax.plot(x, y.ravel())draws one line.- For the 60 values of the histogram runner, with
bins=8andrange=(0, 80)the counts are[0, 8, 20, 0, 11, 18, 3, 0]. What are the heights withdensity=True, and what is the total area?Show answer
Each height is the count divided by , so the heights are 0, 0.0133, 0.0333, 0, 0.0183, 0.03, 0.005 and 0. The total area is the sum of the heights times the width 10, which is . The heights themselves add to 0.1. fig, axes = plt.subplots(2, 3). What isaxes.shape, how do you pick the plot in the second row and third column, and how do you loop over all six?Show answer
The shape is(2, 3). The plot in the second row and third column isaxes[1, 2], since counting starts at 0.for ax in axes.flat:visits all six, row by row.- You save
fig.savefig("a.png", dpi=150)for a figure made withfigsize=(4.5, 3). How many pixels wide and high is the file? What changes if you addbbox_inches="tight"?Show answer
pixels wide and high. Withbbox_inches="tight"the white margins around the plot are trimmed, so the file comes out a little smaller than 675 by 450 (for a simple line plot with axis labels, about 609 by 439); the exact size depends on the labels. - A loss is 3.0, 0.3, 0.03 and 0.003 at epochs 1 to 4. On a linear y-axis from 0 to 3, how high is the last point, and what does a log axis show instead?
Show answer
On the linear axis the last point is at of the height, so it sits on the axis and looks like zero, and the third point is at . On a log axis each value is ten times smaller than the one before, so the four points are equally spaced and fall on a straight line. - A 28 by 28 array
imgof integers between 0 and 255 is a grey-scale photo. Write theimshowcall that shows it correctly with a colour bar, and say whatvmin=0, vmax=255guarantees.Show answer
im = ax.imshow(img, cmap="gray", vmin=0, vmax=255)andfig.colorbar(im, ax=ax). Fixingvminandvmaxmakes 0 always black and 255 always white. Without them the darkest value in this image is drawn black and the brightest white, even if the image is dim, so two images could not be compared. - You plot training and validation accuracy and the figure will be printed in black and white. How do you keep the two lines distinguishable?
Show answer
Do not rely on colour. Give the lines different line styles and markers, such aslinestyle="-", marker="o"andlinestyle="--", marker="s", give each alabeland callax.legend(). Colours from a colour-blind-safe set (for example blue and reddish purple as in this lesson) can stay as an extra signal.
Next: P2.5 loads and cleans tables of data with pandas, whose df.plot() draws these same plots from a column in one line. P3.A9 turns the confusion matrix into precision and recall, and P4.22 shows what each loss-curve shape means.