Skip to content

Data Wrangling·Lesson 33 of 67·intermediate

Plotting with matplotlib

Draw the four charts that answer most questions about a model — line, bar, histogram and scatter — and read the distribution a summary statistic hides.


In this lesson · 18 min

  • →Draw a figure with the explicit fig and ax interface
  • →Choose between line, bar, histogram and scatter
  • →Label every axis, and know why an unlabelled chart is useless
  • →Plot straight from a DataFrame onto an axis you control
  • →Put several charts in one figure, and use a log scale when the data demands it

Charts in these lessons render underneath the code: draw a figure and it appears in the output panel. You do not need plt.show() here — although you do in a script on your own machine, so the examples include it where it belongs.

The figure and the axes

Always create both explicitly. fig is the canvas; ax is the plot on it, and every method you want lives on ax:

PythonPython not started

Lines: something over something else

PythonPython not started

The gap opening between two curves is the picture of overfitting, and it is far more legible than the two final numbers.

Bars: comparing categories

PythonPython not started

DataFrame.plot(..., ax=ax) hands pandas an axis you made, so you keep control of the labels and the figure while pandas does the drawing.

Histograms: the distribution behind the mean

PythonPython not started

Scatter: does one thing track another?

PythonPython not started

Several charts in one figure

plt.subplots(rows, columns) returns an array of axes:

PythonPython not started

Log scales

When values span orders of magnitude, a linear axis shows you one bar and four invisible ones:

PythonPython not started

Plotting a time series

PythonPython not started

Try it yourself

Exercise 1

Draw both series on ax as lines with the labels train and validation, then add the title Loss, the x label step, the y label loss and a legend.

Your turnPython not started
Exercise 2

Draw a histogram of latency on ax with 40 bins, then mark the median with a vertical line. Label the x axis milliseconds.

Your turnPython not started

Check yourself

Your latency has a mean of 380 ms and a median of 210 ms. What does a histogram most likely show?

Check yourself

Why prefer fig, ax = plt.subplots() over calling plt.plot() and plt.title() directly?

Recap

  • Create the figure and axes explicitly with fig, ax = plt.subplots(), and call methods on ax.
  • Line for something over time or steps, bar for categories, histogram for a distribution, scatter for a relationship between two numbers.
  • A histogram shows what a mean hides — multiple populations, skew, a long tail.
  • DataFrame.plot(..., ax=ax) lets pandas draw onto an axis you still control.
  • plt.subplots(rows, cols) gives a grid; set_yscale("log") rescues data spanning orders of magnitude.
  • Title and label every chart, every time.