Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 149 ยท Data and the Web

Statistical Plots with Seaborn

Learn Seaborn step by step. Draw histograms, box plots, scatter plots with hue, bar charts with error bars, heatmaps and pair plots from pandas DataFrames, then style them with themes.

Matplotlib can draw almost anything, but it makes you do the statistics yourself. To compare a measurement across three groups, you would split the data, loop over the groups, compute quartiles, draw boxes and whiskers and add a legend. Seaborn is a library built on top of Matplotlib that does these things for you. You hand it a pandas DataFrame and the names of columns, and it draws a finished, good-looking statistical chart in one line: distributions, group comparisons, relationships and correlation grids.

Because Seaborn is Matplotlib underneath, nothing you learned is wasted. Every Seaborn chart is a Matplotlib figure, so titles, labels and saving work exactly as before. In this lesson you will meet the main chart families, learn why Seaborn insists on "tidy" data, and see the difference between its two kinds of plotting functions.

Setup

Seaborn isn't included with Python or with the in-browser runner, so the examples on this page install it with micropip (see Packages and pip). The first run downloads it and needs an internet connection. On your own computer you would run pip install seaborn in a virtual environment and drop the two micropip lines.

Seaborn ships with sample datasets, but it downloads them from the internet at call time, which doesn't work from the browser sandbox. So every example here builds its own data with NumPy and a fixed random seed. Your charts will match the descriptions, and you will see how to prepare data of your own.

Python Your first Seaborn chart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three ideas appear in that short program, and they repeat throughout Seaborn:

  1. data=df names the DataFrame. After that you refer to columns by name (x="hours_studied"), not by passing arrays.
  2. hue="group" splits the data by a third column and colors it automatically, with a legend you did not have to write.
  3. sns.set_theme() styles everything that follows (grid, fonts, a pleasant color palette).

Tidy data: one row per observation

Seaborn works best on tidy data (sometimes called "long format"): each row is one observation, and each column is one variable. The DataFrame above is tidy: one row per student, with columns for hours, group and score. A "wide" table, with one column per group, needs reshaping first. pandas' melt() does that.

Python Reshaping a wide table with melt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With the tidy table you can write sns.lineplot(data=tidy, x="month", y="sales", hue="region") and get one line per region. If a Seaborn chart looks wrong or a hue has no effect, an untidy table is the usual cause.

Distributions: how are values spread out?

The first question about any numeric column is "what does it look like?" histplot counts values into bins, and kdeplot draws a smooth density curve. Combine them with kde=True. Pass hue to compare groups, and stat="density" so groups of different sizes remain comparable.

Python Histograms and density curves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The left chart shows two humps: a hint that the data mixes two groups. Splitting by hue on the right confirms it. This is Seaborn's strength: the question "does this column hide subgroups?" costs one extra argument.

Note the ax=axes[0] argument. Seaborn's plotting functions accept the Matplotlib axes to draw on, so you can combine them with the layouts from the Matplotlib lesson.

Comparing categories: box, violin and bar charts

When one variable is a category (like a day or a department) and the other is a number, you compare how the number is distributed per category:

  • boxplot shows the median, the middle half of the data (the box) and outliers.
  • violinplot adds the shape of the whole distribution.
  • barplot shows an average per group with a confidence interval. The error bar is computed for you, by bootstrapping.
  • countplot just counts rows per category.
Python Box, violin, bar and count plots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

By default barplot draws the mean with a 95% confidence interval (errorbar=("ci", 95)); here errorbar="sd" shows the standard deviation instead. Whichever you pick, say which one in the caption, because the same bar can look very different. When the group sizes or shapes matter, a box or violin plot is more honest than a bar of averages.

Relationships: scatter, line and regression plots

To see how two numbers move together, use scatterplot. Its hue, size and style arguments encode extra columns as color, dot size and marker shape. lmplot and regplot also fit and draw a regression line with its uncertainty band.

Python Scatter with hue, and a regression fit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The left chart shows engine size against fuel economy, with color for the body type and dot size for weight, so four columns share one picture. The right chart fits a line; the shaded band shows how sure the fit is. Remember that a clear trend is not proof of cause: it only shows that two columns move together.

Heatmaps and pair plots: many variables at once

When you have many numeric columns, two charts give the overview. heatmap turns a table of numbers (typically a correlation matrix) into colored cells, and pairplot draws every column against every other, with distributions on the diagonal.

Python Correlation heatmap and pair plot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a correlation heatmap, use a diverging palette centered at zero (cmap="vlag" with vmin=-1, vmax=1) so that positive and negative correlations are easy to tell apart. annot=True writes the numbers into the cells, which makes the chart usable by readers who cannot distinguish the colors. See Statistical Plots Recipes for the same ideas done by hand in Matplotlib.

Axes-level and figure-level functions

Seaborn has two kinds of plotting functions, and the difference explains most of its surprises.

Kind Examples How it behaves
Axes-level scatterplot, histplot, boxplot, barplot, heatmap Draws onto one Matplotlib axes. Accepts ax=. Returns that axes.
Figure-level relplot, displot, catplot, pairplot, lmplot Creates its own figure, and can split the data into a grid of small charts with col= and row=. Returns a FacetGrid. Does not accept ax=.

Use axes-level functions when you are composing your own layout. Use figure-level functions when you want the same chart repeated for each group (called small multiples).

Python Small multiples with a figure-level function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

One call produced three aligned charts that share their axes, which makes cities directly comparable. g.set_titles and g.set_axis_labels are the figure-level equivalents of ax.set_title and ax.set_xlabel.

Themes and palettes

Looks are controlled in two places:

  • sns.set_theme(style=..., palette=..., context=...). Styles are darkgrid, whitegrid, dark, white and ticks. The context (paper, notebook, talk, poster) scales fonts and lines for where the chart will be shown.
  • Palettes. Use a qualitative palette ("muted", "Set2") for categories, a sequential one ("viridis", "Blues") for ordered values, and a diverging one ("vlag") for values around a midpoint. sns.color_palette("colorblind") gives a palette that stays readable for color-blind readers. Choosing colors carefully matters more than choosing fancy ones.

Because everything is Matplotlib underneath, plt.savefig("chart.png", dpi=150, bbox_inches="tight") saves a Seaborn chart just like any other. Call it before plt.show().

Common mistakes

  • Passing untidy data, then wondering why hue does nothing. Reshape with melt() first.
  • Mixing ax= with figure-level functions. relplot, displot, catplot and pairplot build their own figure. Use scatterplot, histplot and boxplot when you need ax=.
  • Bar charts of averages without saying what the error bar means. State whether it is a confidence interval or a standard deviation.
  • Relying on color alone. Add annot=True, marker style or direct labels for readers who cannot distinguish the colors.
  • Reading a correlation as causation. A heatmap shows that columns move together, not why.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does sns.scatterplot(data=df, x="age", y="income", hue="city") do?

    data names the DataFrame, x and y name columns, and hue colors points by a third column and adds a legend. One chart per group would need a figure-level function with col=.
  2. 2. What does "tidy data" mean for Seaborn?

    Seaborn expects long-format tables. A wide table with one column per group can be reshaped with DataFrame.melt().
  3. 3. Which function can NOT be placed onto an existing Matplotlib axes with ax=?

    relplot is a figure-level function: it creates its own figure and FacetGrid. The others are axes-level functions that draw onto one axes.
  4. 4. Which palette type suits a correlation matrix whose values run from -1 to +1?

    Values on both sides of a meaningful midpoint call for a diverging palette, with vmin=-1, vmax=1 so that zero sits in the neutral middle.
  5. 5. By default, what do the error bars of sns.barplot represent?

    The default is a bootstrapped 95% confidence interval for the mean. You can switch with errorbar="sd" or errorbar=None, and you should say in the caption which one you used.

Summary

  • Seaborn builds statistical charts on top of Matplotlib. You pass a pandas DataFrame with data= and name columns with x=, y= and hue=.
  • Use tidy data (one row per observation); reshape wide tables with melt().
  • Distributions: histplot, kdeplot. Categories: boxplot, violinplot, barplot, countplot. Relationships: scatterplot, lineplot, regplot. Overviews: heatmap, pairplot.
  • Axes-level functions draw onto an axes (ax=); figure-level functions (relplot, displot, catplot, pairplot) make their own figure and small multiples with col= and row=.
  • sns.set_theme() controls style, palette and context. Pick qualitative, sequential or diverging palettes to match your data.
  • Everything remains Matplotlib: titles, labels and savefig work as before.

Next: Machine Learning with scikit-learn, where you will teach a computer to make predictions from data like the data you just plotted.