Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 64 ยท Visualisation

Seaborn Plots from DataFrames: Box, KDE, Pairplot and Heatmap

Draw statistical charts straight from a pandas DataFrame with seaborn: box plots, KDE curves, pair plots and heatmaps, plus pandas' own boxplot and scatter_matrix.

The df.plot(...) methods in Plotting with pandas are quick, but they treat each column as a separate series. Statistical questions are usually about groups ("how does price differ by fuel type?") and relationships ("which columns move together?"). Seaborn is a plotting library built on Matplotlib that is designed for exactly this: you hand it a DataFrame, name the columns for x, y and hue, and it does the grouping, the statistics and the colours.

This lesson shows the four plots you will use most, box plots, KDE curves, pair plots and heatmaps, and then the two close relatives that need nothing but pandas: DataFrame.boxplot and pd.plotting.scatter_matrix.

Note: Seaborn is not part of pandas. On your computer install it with pip install seaborn. In the browser editors the examples install it first with micropip (the first run takes a few seconds). Figures appear below the code.

The seaborn pattern: data, x, y, hue

Every seaborn function follows the same recipe. You pass the whole DataFrame as data= and refer to columns by name:

Python
sns.boxplot(data=df, x="fuel", y="price", hue="gearbox")

Seaborn draws on a Matplotlib Axes, so everything you know about titles, labels and saving (plt.title, ax.set_xlabel, fig.savefig) still applies. Functions that draw onto one Axes accept ax=. A few whole-figure functions (such as pairplot) create their own figure and return a grid object.

We will use a synthetic table of 240 cars with a fixed random seed, so you get the same pictures every time.

Python A synthetic cars table

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.

Box plots by group

A box plot summarises a distribution with five numbers: the box spans the middle 50% of the values (Q1 to Q3), the line inside is the median, the whiskers reach to the most extreme values within 1.5 times the IQR, and dots beyond that are outliers. Putting one box per category next to each other makes group comparisons easy.

Python sns.boxplot: price by fuel type

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.

order=[...] fixes the category order (otherwise it follows the data). Add hue="..." to split each box by a second category, and use sns.violinplot for a smoother shape of the distribution. Because the picture hides how many cars each box represents, print cars["fuel"].value_counts() next to it when sample sizes differ.

KDE: the shape of a distribution

A kernel density estimate (KDE) is a smoothed histogram: instead of counting values in bins it places a small bump at every value and adds the bumps up. The curve is easier to compare across groups than overlapping histograms.

Python sns.kdeplot with hue

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.

fill=True shades the area under each curve. common_norm=False scales every curve to its own area, so small groups are not flattened by big ones. The smoothness is controlled by bw_adjust (try 0.5 for a wigglier curve and 2 for a smoother one). sns.histplot(..., kde=True) draws the histogram and the curve together.

Warning: A KDE can extend beyond the possible range of the data (for example, a price curve that dips below zero). Use cut=0 to stop the curve at the data's minimum and maximum.

Pair plots: every column against every column

sns.pairplot(df) draws a grid: a scatter plot for every pair of numeric columns and a histogram (or KDE) of each column on the diagonal. It is the fastest way to see relationships in a new dataset. Add hue to colour the points by group.

Python sns.pairplot of the numeric columns

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.

Read the bottom row: the price falls as age grows, and falls more gently as mileage grows. The cloud for electric cars sits higher than the others. With k numeric columns you get k ร— k panels, so a pair plot of 15 columns is unreadable. Select the columns you care about first: sns.pairplot(df[["price", "age", "km_thousand", "fuel"]], hue="fuel").

Heatmaps: a table as colour

A heatmap colours the cells of a table by value. Its most common job is showing a correlation matrix: df.corr(numeric_only=True) computes the table, and sns.heatmap draws it. annot=True prints the numbers in the cells, and vmin=-1, vmax=1 with a diverging colormap such as "coolwarm" makes zero the neutral colour.

Python sns.heatmap of a correlation matrix

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.

A heatmap works for any table, not only correlations: a pivot_table of sales by month and region becomes a heatmap with sns.heatmap(pivot, annot=True, fmt=".0f", cmap="Blues"). Colour shows the pattern, and the printed numbers give the exact values. Remember from Correlation Analysis that a high correlation shows that two columns move together, not that one causes the other.

Without seaborn: DataFrame.boxplot and scatter_matrix

pandas has its own versions of two of these charts, so you can get a quick look without another library.

df.boxplot(column="price", by="fuel") draws one box per group. pd.plotting.scatter_matrix(df) is the pandas twin of pairplot: a grid of scatter plots with histograms on the diagonal (diagonal="kde" draws curves instead, but needs SciPy). They look plainer than seaborn's, but they need only pandas and Matplotlib, and they run anywhere.

Python DataFrame.boxplot and scatter_matrix

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="fuel" makes pandas group first. The default title of a grouped box plot is "Boxplot grouped by fuel", which is why the example clears it and sets a shorter one with suptitle.

Which plot answers which question?

Box plot Compare groups
KDE Compare shapes
Pair plot Scan every pair
Heatmap Show a table as colour

Pick by question, not by looks.

1 / 2

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In sns.boxplot(data=df, x='fuel', y='price'), what do x and y refer to?

    Seaborn takes the DataFrame as data= and finds the columns by name. It also uses the names as default axis labels.
  2. 2. What does common_norm=False do in sns.kdeplot(..., hue='fuel')?

    With common_norm=True the curves share one total area, so a small group looks flat. Setting False normalises each group separately.
  3. 3. Why should you select columns before calling sns.pairplot on a wide DataFrame?

    The grid has one panel for every pair of columns, so the number of panels grows with the square of the number of columns.
  4. 4. Which pandas-only function is the counterpart of sns.pairplot?

    scatter_matrix draws a grid of scatter plots for numeric columns with histograms on the diagonal (or KDE curves with diagonal="kde", which needs SciPy).
  5. 5. What do vmin=-1, vmax=1 and cmap='coolwarm' do for a correlation heatmap?

    A diverging colormap with symmetric limits puts zero in the middle, so positive and negative relationships get opposite colours.

Summary

  • Seaborn functions take data=df and column names for x, y and hue; they return Matplotlib objects you can still customise.
  • boxplot compares groups, kdeplot compares distribution shapes, pairplot scans every pair of columns, heatmap shows a table as colour.
  • Use corr(numeric_only=True) with annot=True, a diverging colormap and vmin=-1, vmax=1 for correlation heatmaps.
  • Select a few columns before pairplot, and set common_norm=False and cut=0 for honest KDEs.
  • df.boxplot(column=..., by=...) and pd.plotting.scatter_matrix(df) give plainer versions with pandas alone.

Next: Styling and Displaying Tables covers how to make the tables themselves readable.