seaborn and tidy data
Last updated
With matplotlib you say where every dot goes and what colour it is. seaborn works one level up: you hand it a tidy table and name the columns, and it works out the positions, the colours, the legend and the labels. In this lesson you'll meet the penguins this stage draws, map columns to a chart, see the two kinds of seaborn function, change the look with themes, and fix the most common seaborn error: a wide table where it wants a long one.
By the end of this lesson you can
- Draw a seaborn chart by naming a table's columns with data=, x=, y= and hue=
- Tell figure-level functions from axes-level ones, and use each
- Change the look of every chart with sns.set_theme
- Reshape a wide table to long with melt before plotting it
Meet the penguins
Stage 6 drew charts the matplotlib way: make the figure and axes, then call ax.plot, ax.bar or ax.scatter with the numbers. That gives you control over everything, and it means a lot of code for a chart with colours by group and a legend.
seaborn is a library built on matplotlib for statistical charts: charts that show how a variable is spread out, how groups compare, how two variables relate. You give it a pandas table and the names of columns. It draws with matplotlib underneath, so everything from Stage 6 (titles, labels, ax.set_ylim, saving) still works on what it makes.
Most examples in this stage use the Palmer Penguins data: measurements of 344 penguins of three species, taken on three islands near Palmer Station in Antarctica from 2007 to 2009 by Dr Kristen Gorman's team. It's free to use for anything (CC0), small enough to see, and has numbers and groups to compare. Run the cell.
Every row is one penguin, every column one thing measured about it: species, island, bill length and depth, flipper length (all in millimetres), body_mass_g in grams, sex and the year. That's a tidy table, as in lesson 5.5, and it's the shape seaborn wants.
Name the columns
Run the cells. The first reads the table again and draws the smallest seaborn chart: a table and two columns.
data=penguinsis the table;x=andy=name the columns for across and up. seaborn labels the axes with the column names by itself.- The first cell's
Outis<Axes: xlabel='flipper_length_mm', ylabel='body_mass_g'>: seaborn drew on a matplotlib axes and handed it back. That's why the second cell can keep it asaxand callax.set_titleandax.set_xlabel, just as in Stage 6. Ending the last line with;hides theOut. hue="species"colours each dot by its species and adds a legend.style="sex"gives males and females different marker shapes. You never wrote a loop over species or picked a colour.
The chart answers a real question: heavier penguins have longer flippers, and the three species sit in different places. Gentoos (the orange group) are the biggest.
Choosing which column goes where is called mapping columns to the chart's aesthetics: position, colour, size, shape. Try it:
sns.scatterplot(data=penguins, x="flipper_length_mm", y="body_mass_g", hue="species") Each pink line is one argument of the call. You never tell seaborn where a dot goes or what colour it is: you name the columns, and it works out the axes, the colours and the legend.
Two kinds of function
seaborn has two kinds of plotting function, and the difference matters as soon as you want more than one chart.
| Kind | Examples | Draws on | Returns |
|---|---|---|---|
| Axes-level | scatterplot, histplot, boxplot, lineplot | one axes: the current one, or the one you pass as ax= | the matplotlib Axes |
| Figure-level | relplot, displot, catplot | a new figure it makes itself, with one or more axes | a seaborn FacetGrid |
Run the cells.
- The first cell makes a figure with two axes the Stage 6 way, then gives each axes-level function its axes with
ax=axs[0]andax=axs[1]. That's how you put seaborn charts side by side, or beside matplotlib ones. - The second cell calls
sns.displot, the figure-level function for distributions.col="island"makes one chart per island, with shared axes, titles likeisland = Biscoeand one legend. It made its own figure, so it can't go into an axes you made; it returns aFacetGrid, which has its own methods, likeg.set_axis_labelsfor every panel at once.
Each figure-level function wraps a family of axes-level ones: relplot for scatter and line charts, displot for histograms and density curves, catplot for charts by category. Lesson 7.6 uses them for small multiples. A good rule: reach for figure-level when you want panels by a column, axes-level when you're arranging the figure yourself.
Themes
Run the cells. sns.set_theme() sets matplotlib's defaults for every chart after it, until you change them again.
style=sets the background and grid:"darkgrid"(the default),"whitegrid","dark","white"or"ticks".context=scales text and lines for where the chart will be seen:"paper","notebook"(the default),"talk"or"poster", from small to big.palette=sets the colours used for groups."colorblind"is seaborn's version of a colour-blind-safe set (lesson 6.7).sns.set_theme()with nothing in the brackets goes back to seaborn's own look: the grey background is#EAEAF2, with white grid lines.
sns.set_theme changes matplotlib's settings, so it also changes charts you draw with plain matplotlib afterwards. In this page, each notebook starts from matplotlib's plain defaults again; on your computer a theme lasts until the kernel restarts. Set the theme once, in the first cell, so every chart in a notebook looks alike.
Wrong way: a wide table
Back to the Tindahan stores. A pivot table is the natural way to get each store's weekly sales side by side, so it's tempting to plot it straight away. Run the cells.
wide has one column per store and the weeks as its index. It's a fine table for reading, but there is no column called kilos and no column called store: those words are only in the header. So seaborn says it could not interpret value kilos for y: an entry with this name does not appear in data.
seaborn's x=, y= and hue= each name one column. A tidy, long table has a column for each of those, and one row per week per store. melt (lesson 5.5) turns wide into long: id_vars="date" keeps the date as a column, the store names go into a new column called store, and the numbers into one called kilos. Eight weeks of four stores is 32 rows. Then the call works, and draws one line per store with a legend.
(seaborn can draw a wide table too, if you pass only data=wide and no x or y: it draws each column as a line. But as soon as you want to name what goes where, you need it long.)
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Waskom, seaborn: statistical data visualization, Journal of Open Source Software 6(60), 2021: what seaborn is for, and how it builds on matplotlib and pandas
- seaborn: Overview of seaborn plotting functions: figure-level against axes-level functions
- seaborn: Data structures accepted by seaborn: long-form and wide-form data
- seaborn: Controlling figure aesthetics: set_theme, styles and contexts
- Gorman, Williams and Fraser, Ecological Sexual Dimorphism and Environmental Variability within a Community of Antarctic Penguins, PLOS ONE 9(3), 2014: where the penguin measurements come from
- Horst, Hill and Gorman, palmerpenguins: Palmer Archipelago (Antarctica) penguin data, 2020: the penguins dataset, released under CC0