HuntExams Academy logo
Data Science · Chapter 15 of 43

Seaborn Basics

seaborn is a higher-level plotting library built on matplotlib. It ships great defaults and one-liner statistical plots.

Great for EDA — histplot, boxplot, heatmap, pairplot.

Example 1 (python)
import seaborn as sns
import pandas as pd
df = pd.read_csv('data.csv')
sns.histplot(df['age'], bins=20)

Fast histogram with sensible defaults.

Example 2 (python)
sns.heatmap(df.corr(numeric_only=True), annot=True)

Correlation heatmap.

Key points

  • Built on matplotlib.
  • Great defaults for statistical plots.
  • Common plots: hist, box, bar, heatmap, pairplot.
  • Ideal during EDA.
💡 Note: Use seaborn for exploration, matplotlib when you need pixel-perfect control.

Understanding Seaborn Basics

Seaborn helps you ask statistical questions through graphics. It builds on Matplotlib, which supplies the underlying figures, axes, and drawing tools. Seaborn adds convenient ways to map table columns to visual features and summarize observations. During exploratory data analysis (EDA), the goal is not merely an attractive chart: it is to understand distributions, compare groups, and identify relationships worth investigating.

Start with a table whose meaning is clear. In long-form data, each row represents an observation and each column represents a variable. For example, one row might describe one delivery, with columns for delivery method and duration in minutes. A typical call such as sns.histplot(data=df, x="minutes") names the table and the variable explicitly. Adding hue="method" separates observations by color; it does not change what one row represents.

Choose a plot according to the question. A histogram divides a numeric range into intervals and counts observations within them. Its appearance depends on bin boundaries: wide bins hide detail, while narrow bins can exaggerate small fluctuations. A boxplot compares medians and quartiles across groups. Its default whiskers reach the most extreme observations within 1.5 interquartile ranges of the box; points beyond them are not automatically mistakes. A scatterplot shows paired numeric measurements, while pairplot builds a grid of relationships among selected variables.

Distinguish raw observations from summaries. Seaborn's barplot estimates a numeric summary, usually a mean, for each category; countplot counts observations. A heatmap colors cells of a supplied matrix. When that matrix contains correlations, pandas computes the correlations and Seaborn displays them. Pearson correlation describes linear association, not causation, and a small value does not rule out a nonlinear relationship.

Seaborn and Matplotlib are complementary rather than competing choices. Axes-level functions such as histplot return a Matplotlib Axes that you can label or customize. Figure-level functions such as displot and pairplot manage a larger layout themselves. Attractive defaults cannot repair missing observations, inconsistent units, or an unrepresentative sample. Before interpreting a graphic, establish what was measured, which rows were included, and whether the displayed statistic answers your question. A useful caption states these choices so readers can distinguish evidence from presentation.

Practical walkthrough

Consider the question: how do recorded delivery times differ between standard and express service? Assume every row describes a different completed delivery and all durations use minutes. The miniature dataset below is illustrative, not a representative sample of either service.

First, inspect the columns and observational unit. Check that durations are numeric, that category labels are consistent, and that duplicate records do not accidentally count one delivery twice. The supplied pandas guide identifies inspection, missing-data handling, and grouping as distinct tasks; do these deliberately rather than expecting a plotting function to clean the table.

Second, count missing durations before excluding them. Here, one standard delivery lacks a duration. Dropping it enables a numeric comparison, but the result describes only recorded durations. If slow deliveries are more likely to have missing values, the visible distribution could be misleading.

Third, choose shared bins: 0–10, 10–20, and 20–30 minutes. The example assigns intervals that include their left boundary and exclude their right boundary. All observed durations fall strictly inside these intervals, avoiding ambiguity at endpoints. Printing counts makes the proposed histogram auditable without rendering a plot.

For a subsequent visualization, use sns.histplot with data=clean, x="minutes", hue="method", bins=[0, 10, 20, 30], and multiple="dodge". This places group bars beside each other. Counts answer how many deliveries occupy each interval. With unequal group sizes, consider separately normalized proportions when comparing shapes instead of volumes.

Finally, label the horizontal axis with minutes and report retained group sizes. Check whether another reasonable bin width changes the apparent story. Describe the sample difference without claiming that service choice caused it.

Worked example

import pandas as pd

# Verify the data behind a Seaborn histogram without creating a plot.
df = pd.DataFrame({
    "method": ["standard"] * 5 + ["express"] * 4,
    "minutes": [12, 18, 22, 28, None, 4, 8, 14, 16],
})

print(f"Missing durations: {df['minutes'].isna().sum()}")
clean = df.dropna(subset=["minutes"]).copy()
labels = ["0-<10", "10-<20", "20-<30"]
clean["interval"] = pd.cut(
    clean["minutes"], bins=[0, 10, 20, 30],
    labels=labels, right=False
)

for method in ["standard", "express"]:
    group = clean.loc[clean["method"] == method]
    counts = group["interval"].value_counts().reindex(labels, fill_value=0)
    print(f"{method}: n={len(group)}, mean={group['minutes'].mean():.1f}")
    print("  " + ", ".join(f"{label}: {int(counts[label])}" for label in labels))

Expected output

Missing durations: 1
standard: n=4, mean=20.0
  0-<10: 0, 10-<20: 2, 20-<30: 2
express: n=4, mean=10.5
  0-<10: 2, 10-<20: 2, 20-<30: 0

This self-contained example requires pandas and deliberately produces text rather than a plot. It checks the observations and counts that a grouped Seaborn histogram would summarize. Standard deliveries occupy the middle and upper intervals; express deliveries occupy the lower and middle intervals. Both retained groups contain four observations, so their counts are directly comparable in this example. The means provide additional context but are not histogram bar heights. One missing standard duration remains an important limitation. These eight recorded deliveries suggest a sample difference, not a reliable population estimate or evidence that selecting express service necessarily reduces an individual delivery's duration.

Common mistakes and how to avoid them

  • Using barplot when you want category frequencies.

    Use countplot for row counts. Use barplot for a numeric summary and identify the estimator and uncertainty display; a mean bar does not show the full distribution.

  • Treating missing values or boxplot outliers as disposable.

    Report missing counts and inspect unusual records against their source. Exclude values only for a documented reason, such as an impossible unit or confirmed recording error.

  • Reading a correlation heatmap as a causal explanation.

    Inspect scatterplots, sample sizes, and plausible confounding variables. Exclude numeric identifiers from correlations. Describe association, and remember that missing-value patterns can give different pairs different effective samples.

  • Using the test set to guide exploratory feature choices.

    If EDA supports predictive modeling, reserve the test set first. Make feature decisions using training data, fit preprocessing on training data only, and apply those fitted transformations unchanged during evaluation.

Review questions

What does hue add to a Seaborn call?

It maps another variable to color. For categorical delivery methods, it distinguishes groups within the same plotting space without changing the observational unit.

Why inspect more than one histogram bin width?

Bins determine which observations are combined. A feature that disappears under a modest boundary change may reflect grouping choices rather than a stable distributional pattern.

What is lost when comparing groups only by mean bars?

Means conceal spread, skewness, and unusual observations. Groups with similar means can have very different distributions; boxplots or individual observations provide complementary information.

What conclusion does the worked example support?

Recorded standard deliveries have a higher sample mean and occupy higher intervals. The small illustrative sample and missing duration prevent a confident generalization, and no causal effect is established.

Further reading

📝 Quick Quiz

1. seaborn sits on top of:

2. A correlation heatmap uses:

3. seaborn is best for: