Definition
Do boys and girls in your district score differently in maths? Do marks rise with attendance? A single statistical chart, a box plot by group or a scatter with a trend line, can answer such questions in seconds, and seaborn makes these charts in one line.
Statistical charts summarise distributions and relationships rather than individual values. Common types are histograms and density curves (one variable's distribution), box plots and violin plots (comparing distributions across groups), scatter plots with regression lines (relationships between two variables), heatmaps (a grid such as a correlation matrix) and pair plots (all pairwise relationships). Seaborn, a library built on Matplotlib by Michael Waskom, creates these from a pandas DataFrame with functions such as histplot, boxplot, violinplot, regplot, heatmap and pairplot.
In simple words
A box plot is like a summary card for a group: the middle line is the typical student, the box holds the middle half of the class, and the whiskers show how far the rest stretch. Put several boxes side by side and you compare groups at a glance.
Overview
- seaborn, created by Michael Waskom, is built on matplotlib and makes statistical charts from DataFrames in one line.
- It works best with long-format data: one row per observation, one column per variable.
- hue, size and style map extra variables to colour, size and marker.
- Many seaborn functions compute statistics for you, such as means with confidence intervals or regression lines.
- Figure-level functions (relplot, displot, catplot) create grids of panels with col and row.
- This site's browser runtime has no seaborn, so the course shows the same charts with matplotlib.
Why it matters
Averages hide spread, outliers and differences between groups. Statistical charts show the whole shape of the data, which is essential before choosing a model or drawing a conclusion, and they make comparisons fair and visible.
Key terms
- Box plot
- Shows the median, quartiles and outliers of a distribution.
- Violin plot
- A box plot combined with a smoothed density, showing the full shape.
- Density curve (KDE)
- A smooth version of a histogram estimating how values are distributed.
- Regression line
- The best-fit straight line through a scatter plot.
- Correlation heatmap
- A coloured grid of correlation coefficients between pairs of variables.
- Hue
- A seaborn option that colours points or bars by a category.
Types
seaborn groups its chart functions into families by the kind of question they answer. These are the main types.
1. Relational plots
Charts of how two numeric variables relate: scatterplot and lineplot (relplot for grids).
- How it works: lineplot averages repeated x values and draws a confidence band; hue splits the data into coloured groups.
- Example: sns.lineplot(data=df, x="month", y="aqi", hue="city").
- When to use it: Use them to compare trends between groups and explore relationships. The confidence band shows how sure the average is.
2. Distribution plots
Charts of how one variable's values are spread: histplot, kdeplot, ecdfplot and rugplot (displot for grids).
- How it works: kdeplot draws a smooth estimate of the distribution; hue overlays groups for comparison.
- Example: sns.histplot(data=df, x="marks", hue="gender", kde=True).
- When to use it: Use them to check skew and compare the spread of groups. Density curves can hide small samples, so check the counts too.
3. Categorical plots
Charts comparing a numeric variable across categories: barplot, countplot, boxplot, violinplot, stripplot and swarmplot (catplot for grids).
- How it works: barplot shows the mean with an error bar; boxplot shows quartiles; violinplot adds the distribution's shape.
- Example: sns.boxplot(data=df, x="city", y="delivery_minutes").
- When to use it: Use them to compare groups fairly, showing spread and not just averages.
4. Regression plots
Scatter plots with a fitted line: regplot and lmplot.
- How it works: They fit a linear (or polynomial, or logistic) model and draw it with a confidence band.
- Example: sns.regplot(data=df, x="area", y="price") for house prices.
- When to use it: Use them for a quick look at whether a linear relationship is plausible. Look at the scatter around the line as well, since one outlier can pull it.
5. Matrix and multi-variable plots
heatmap, clustermap, pairplot and jointplot.
- How it works: heatmap colours a table such as a correlation matrix; pairplot draws every pair of numeric columns; jointplot adds distributions on the margins.
- Example: sns.heatmap(df.corr(numeric_only=True), annot=True) to spot related features.
- When to use it: Use them during EDA to scan many relationships at once. Pair plots get slow with many columns, so choose the most relevant ones first.
Explained in detail
Seaborn functions and their Matplotlib equivalents
Seaborn works best with "tidy" data: one row per observation and one column per variable. You pass the DataFrame and column names, and seaborn handles grouping, colours and legends. The browser Python on this site includes Matplotlib but not seaborn, so the runnable example draws the same statistical charts with Matplotlib and NumPy; on your own computer, install seaborn with pip install seaborn and use the one-line versions in the table.
| Chart | Seaborn | Matplotlib equivalent |
|---|---|---|
| Histogram with density | sns.histplot(df, x="marks", kde=True) | ax.hist(df["marks"], bins=20) |
| Box plot by group | sns.boxplot(df, x="school_type", y="marks") | ax.boxplot([g["marks"] for _, g in df.groupby("school_type")]) |
| Scatter with trend | sns.regplot(df, x="attendance", y="marks") | ax.scatter(...) plus np.polyfit for the line |
| Correlation heatmap | sns.heatmap(df.corr(numeric_only=True), annot=True) | ax.imshow(corr) plus text labels |
| All pairwise relationships | sns.pairplot(df, hue="school_type") | A grid of scatter plots with plt.subplots |
Reading statistical charts carefully
In a box plot the line inside the box is the median, the box spans the first to third quartile (the middle 50 per cent) and the whiskers usually reach to the furthest point within 1.5 times the interquartile range; points beyond are drawn individually as possible outliers. Overlapping boxes suggest groups are similar, but do not prove it; a formal test or more data may be needed. A regression line shows the average trend, not a law: the scatter around it shows how much individuals vary, and correlation does not prove causation. Attendance and marks may both rise because of a third factor, such as family support. In a correlation heatmap, remember that correlation measures only straight-line relationships and is sensitive to outliers, so always look at the scatter plots too.
Choosing between these charts depends on how many observations you have and what you want to compare. With only a handful of values per group, show the individual points, for example as a strip plot, because a box summarising five numbers can mislead. With hundreds of values, box and violin plots summarise well. When groups have very different sizes, mention the count of each so readers do not over-interpret a small group. For relationships, a scatter plot with transparent points avoids hiding dense areas, and a heatmap is useful only once you have several variables to compare. Whatever you choose, the aim is the same: let the reader see both the typical value and the variation around it.
How it works
- Put the data in tidy form: one row per observation.
- Look at each variable's distribution with a histogram or density curve.
- Compare groups with box or violin plots.
- Explore relationships with scatter plots, trend lines and a correlation heatmap.
- Write down what each chart shows and what it does not prove.
In code
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
rng = np.random.default_rng(1)
n = 300
school = rng.choice(["Government", "Private", "Aided"], size=n, p=[0.5, 0.3, 0.2])
attendance = np.clip(rng.normal(82, 9, n), 45, 100)
study_hours = np.clip(rng.normal(2.0, 0.8, n), 0, 5)
marks = np.clip(20 + 0.45 * attendance + 6 * study_hours + rng.normal(0, 8, n), 0, 100)
df = pd.DataFrame({"school": school, "attendance": attendance, "study_hours": study_hours, "marks": marks})
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
groups = [g["marks"].values for _, g in df.groupby("school")]
axes[0].boxplot(groups) # like sns.boxplot(df, x="school", y="marks")
axes[0].set_xticks(range(1, 4), sorted(df["school"].unique()))
axes[0].set_title("Marks by type of school")
axes[0].set_ylabel("Maths marks (out of 100)")
slope, intercept = np.polyfit(df["attendance"], df["marks"], 1) # like sns.regplot
axes[1].scatter(df["attendance"], df["marks"], s=10, alpha=0.5)
xs = np.linspace(45, 100, 50)
axes[1].plot(xs, slope * xs + intercept, color="crimson")
axes[1].set_title("Marks rise with attendance")
axes[1].set_xlabel("Attendance (%)")
corr = df[["attendance", "study_hours", "marks"]].corr() # like sns.heatmap(corr, annot=True)
im = axes[2].imshow(corr, cmap="Blues", vmin=-1, vmax=1)
axes[2].set_xticks(range(3), corr.columns, rotation=20)
axes[2].set_yticks(range(3), corr.columns)
for i in range(3):
for j in range(3):
axes[2].text(j, i, f"{corr.iloc[i, j]:.2f}", ha="center", va="center")
axes[2].set_title("Correlation heatmap")
fig.colorbar(im, ax=axes[2])
fig.tight_layout()
print(df.groupby("school")["marks"].describe()[["count", "25%", "50%", "75%"]].round(1))
print(f"Trend: about {slope:.2f} extra marks per extra percentage point of attendance")
print("Correlations with marks:", corr["marks"].drop("marks").round(2).to_dict())Output
count 25% 50% 75%
school
Aided 56.0 61.0 69.1 74.3
Government 153.0 61.2 68.0 75.1
Private 91.0 62.0 69.3 76.9
Trend: about 0.43 extra marks per extra percentage point of attendance
Correlations with marks: {'attendance': 0.37, 'study_hours': 0.47}Try it yourself
Match the question to the statistical chart
Which chart helps most?
- Do three types of school differ in marks?
- Which pairs of variables move together?
- Does marks rise with attendance, and by how much?
- What is the full shape of one group's marks?
Valid conclusion or overreach?
Judge each conclusion from the charts.
"Median marks are higher in private schools in this sample"
"Government schools are worse"
"Study hours and marks are positively correlated"
"Attending more classes causes higher marks for every student"
Common mistakes
- Comparing groups by averages alone, ignoring spread.
- Treating a trend line or correlation as proof of cause.
- Reading a heatmap without checking the scatter plots behind it.
Check yourself
Summary
- Statistical charts show distributions and relationships: histograms, box and violin plots, regression scatters and heatmaps.
- Seaborn draws them in one line from tidy DataFrames; Matplotlib can draw the same charts directly.
- Read them carefully: spread matters, and correlation is not causation.
Finished reading?
Sources: seaborn: user guide and tutorial · Claus O. Wilke, Fundamentals of Data Visualization