seaborn and interactive charts · lesson 1 of 10
Parts in this lesson
Aimport seaborn as snsthe usual short name
Bsns.scatterplot(data=df, x="a", y="b", hue="g")columns mapped to position and colour
Csns.displot(..., col="g")a figure-level function: makes its own figure
Dsns.set_theme(style="whitegrid")one look for every chart after it
Edf.melt(id_vars="date")5.5: wide to long

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.

penguins.ipynb

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.

scatter.ipynb
  • data=penguins is the table; x= and y= name the columns for across and up. seaborn labels the axes with the column names by itself.
  • The first cell's Out is <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 as ax and call ax.set_title and ax.set_xlabel, just as in Stage 6. Ending the last line with ; hides the Out.
  • 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:

Mapping linescolumns of a tidy table, mapped to the chart
sns.scatterplot(data=penguins, x="flipper_length_mm", y="body_mass_g", hue="species") speciesAdelieGentooChinstrapAdelieislandTorgersenBiscoeDreamDreambill length39.146.846.136bill depth18.715.418.218.5flipper length181215178186body mass3750515032503100sexmalemalefemalefemale… 342 rows, one per penguinflipper_length_mmbody_mass_gAdelieChinstrapGentoohue

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.

KindExamplesDraws onReturns
Axes-levelscatterplot, histplot, boxplot, lineplotone axes: the current one, or the one you pass as ax=the matplotlib Axes
Figure-levelrelplot, displot, catplota new figure it makes itself, with one or more axesa seaborn FacetGrid

Run the cells.

levels.ipynb
  • 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] and ax=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 like island = Biscoe and one legend. It made its own figure, so it can't go into an axes you made; it returns a FacetGrid, which has its own methods, like g.set_axis_labels for 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.

themes.ipynb
  • 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.

weekly.ipynb

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

What does sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm") return?
You want a histogram and a box plot side by side in a figure you made with plt.subplots(1, 2). Which functions?
A table has columns month, rice, sugar and oil. What must you do before sns.lineplot(data=t, x="month", y="kilos", hue="item")?

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.

All sources for Simple Data Analysis