Skip to main content

P02.8 · Plotting with Matplotlib and seaborn

A free, illustrated module of 4 lessons and one interactive in P02 Scientific Python: NumPy, pandas and Plotting: Figure, Axes and a first line plot; Scatter, bar and histogram; Several panels, one style; seaborn: plots from tidy tables.

P02.8 L1 · Core 4 lessons · about 100 min Live · in review

Part of P02 Scientific Python: NumPy, pandas and Plotting in the Programming and Data track.

A plot is a scale: a rule that turns data numbers into pixel positions. These four lessons place the course’s weather readings in a pixel box by hand before Matplotlib’s Figure and Axes do it, add scatter plots, bar charts and histograms (counted by hand first), lay several panels on one shared scale, and end with seaborn, which draws a whole long table in one call and computes group means before it draws them.

What you need first. NumPy arrays, their reductions and slices (P02.1 to P02.3), pandas DataFrames (P02.4), the long table readings of P02.5.3, and group-by (P02.6) for the last lesson. Functions (P01.4) and loops (P01.3) are used throughout.

Lessons

  1. Figure, Axes and a first line plot P02.8.1 25 min

    A plot is a scale: a rule that turns data numbers into pixel positions. Place four valley temperatures in a 400 by 300 pixel box by hand, write them as an SVG line, then let Matplotlib’s Figure and Axes do the same, and check its numbers against yours.

  2. Scatter, bar and histogram P02.8.2 25 min

    Three more calls on the same Axes, each for one kind of question: ax.scatter for two numeric columns, ax.bar for one number per category, ax.hist for the spread of one column. Count a histogram by hand, check it against NumPy, and see how the choice of bins changes the picture.

  3. Several panels, one style P02.8.3 25 min

    Place three panels by hand with fig.add_axes in fractions of the figure, then let plt.subplots do it: an array of Axes, one station per panel on a shared y axis. Mark values with axhline and annotate, label lines directly, and keep the styling in one function.

  4. seaborn: plots from tidy tables P02.8.4 25 min

    seaborn maps the columns of a long table to x, y and hue. Draw temperature by day coloured by station as a Matplotlib loop over groups, then in one seaborn call; meet axes-level and figure-level functions on iris, and see that barplot and lineplot compute a mean before they draw.

The interactive

P02.8-X1 · Figure anatomy. A small chart of the valley temperatures with a switch for each part: title, axis labels, ticks, grid, legend, data line and a second panel. Switching a part on outlines it, names the Matplotlib object it belongs to and shows the line of code that makes it; two sliders set the y limits and the read-out works out where Monday’s reading lands. It lives in Figure, Axes and a first line plot.

Back to top