Seaborn#
In the previous chapter, we introduced Matplotlib and used it to build a foundation for creating clear, interpretable visualizations. Matplotlib provides fine-grained control and makes the mechanics of plotting explicit, which is valuable for understanding how visualizations are constructed. However, that level of control can also lead to verbose code and repetitive patterns, especially during exploratory data analysis.
This chapter introduces Seaborn, a higher-level visualization library built on top of Matplotlib. Seaborn is designed specifically for exploratory and statistical visualization. Rather than focusing on low-level drawing commands, it emphasizes semantic mappings—connecting variables in a dataset directly to visual encodings such as position, color, and grouping.
Seaborn does not replace Matplotlib. Instead, it builds on it. All Seaborn plots ultimately produce Matplotlib figures and axes, and many Matplotlib concepts still apply. The difference lies in how much work is done automatically and how strongly the library encourages certain best practices.
Seaborn offers several advantages over using Matplotlib alone during exploratory analysis:
Better default aesthetics: Seaborn produces visually balanced, readable plots out of the box, reducing the need for manual styling during early exploration.
High-level interface: Complex plots often require significantly less code, allowing analysts to focus on questions rather than plotting mechanics.
Built for pandas: Seaborn works naturally with pandas DataFrames and tidy (long-form) data, aligning well with common data preparation workflows.
Statistical visualizations: Many functions include built-in support for aggregation, confidence intervals, and distributional summaries.
Sophisticated color palettes: Seaborn provides thoughtfully designed color schemes that support categorical and continuous comparisons without additional configuration.
The goal of this chapter is not to catalog every Seaborn function, but to show how Seaborn can be used to answer the same types of analytical questions explored in the Matplotlib chapter—often more concisely and with stronger defaults. The structure of this chapter mirrors the previous one, organizing plots around common question types such as comparisons, change over time, distributions, relationships, and composition.
Throughout the chapter, we will continue to use the Dirty Café dataset and the same prepared DataFrames created earlier. This allows direct comparison between Matplotlib and Seaborn approaches and reinforces that the key differences lie in how plots are specified, not in how the data is cleaned or structured.
By the end of this chapter, you will be able to use Seaborn to quickly generate common exploratory visualizations, understand what Seaborn does automatically on your behalf, and recognize when it is appropriate to rely on Seaborn’s abstractions versus dropping down to Matplotlib for finer control.
Seaborn’s Data Model#
Seaborn is built around a specific model of how data should be structured and how variables should be mapped to visual elements. Understanding this model is essential for using Seaborn effectively, as many of its conveniences rely on assumptions about data shape and intent.
At its core, Seaborn expects data to be in tidy (long-form) format, where each column represents a variable and each row represents an observation. This aligns naturally with pandas DataFrames and with the data-shaping practices introduced earlier in the book. In contrast to Matplotlib, which often requires manual reshaping or explicit iteration, Seaborn uses column names directly to define how data is encoded visually.
Most Seaborn plotting functions follow the same basic pattern. Variables from a DataFrame are mapped to visual encodings using semantic arguments such as:
xandyfor positionhuefor grouping by colorsizefor relative magnitudestylefor line or marker variation
These mappings describe what should be compared, while Seaborn determines how those comparisons are rendered. For example, specifying a categorical variable for hue automatically creates grouped plots with a legend, without requiring manual splitting or looping.
Another key feature of Seaborn’s data model is automatic aggregation. For certain plot types—such as bar plots and line plots—Seaborn will aggregate data internally if multiple observations map to the same visual position. By default, this aggregation is typically the mean, accompanied by a confidence interval. While this behavior can be convenient, it is important to recognize when aggregation is happening and to override it when necessary.
This differs from the Matplotlib approach used in the previous chapter, where aggregation was always performed explicitly before plotting. Seaborn’s approach reduces code, but it also shifts some responsibility from the user to the library. As a result, analysts must be especially attentive to the grain of the data being plotted and to whether implicit aggregation matches the analytical question.
Because Seaborn builds on Matplotlib, it still produces standard Matplotlib figure and axes objects. This means that Seaborn plots can be further customized using Matplotlib commands, and that concepts such as axes labels, limits, and annotations behave as before. The key difference is that Seaborn emphasizes semantic intent over drawing primitives, allowing complex visualizations to be specified declaratively.
In the sections that follow, we will use Seaborn to recreate many of the same visualizations introduced earlier, highlighting how the data model enables more concise code while reinforcing the importance of deliberate data preparation and interpretation.
Setup and Styling Defaults#
Before creating any plots, it is useful to understand how Seaborn configures visual style and how those settings interact with Matplotlib. One of Seaborn’s defining features is that it applies a set of sensible styling defaults automatically, producing readable plots without requiring manual configuration.
Seaborn is typically imported alongside Matplotlib and pandas:
1import matplotlib.pyplot as plt
2import numpy as np
3import pandas as pd
4import seaborn as sns
When Seaborn is imported, it does not immediately change Matplotlib’s appearance. However, Seaborn provides functions that set global plotting parameters, affecting all subsequent plots created in the session. The most common entry point is set_theme, which establishes a baseline style, color palette, and font scaling:
sns.set_theme()
Calling set_theme updates Matplotlib’s runtime configuration so that both Seaborn and Matplotlib plots share a consistent visual appearance. This is intentional: Seaborn is designed to integrate seamlessly with Matplotlib rather than operate as a separate system.
Seaborn themes are designed to support exploratory analysis by emphasizing legibility and contrast. Gridlines, font sizes, and color choices are tuned to make patterns easier to see, especially when plotting multiple groups or dense data. In many cases, these defaults are sufficient and should be accepted rather than customized.
Seaborn also provides more specific controls for context and style. The plotting context adjusts the scale of visual elements to match the intended use (for example, notebooks versus presentations), while the style controls background elements such as grids and spines. These options allow minor adjustments without requiring direct manipulation of Matplotlib settings.
An important implication of Seaborn’s styling approach is that it operates globally. Once a theme or style is set, it affects all plots that follow, including those created directly with Matplotlib. For this reason, theme configuration should typically be done once, near the top of a notebook or script, rather than repeatedly throughout the code.
Data Load#
The following code loads the dataset and computes the derived variables from the previous chapter.
1from clean import clean_dirty_cafe_strings, limited_cafe_columns
2
3df = pd.read_csv("resources/data/dirty_cafe_strings.csv")
4df = clean_dirty_cafe_strings(df)
5df = limited_cafe_columns(df)
6
7# Note, Datetime_UTC is not unique, so we cannot set it as the index
8# this would cause issues with seaborn
9
10columns = {"Item_norm": "Item",
11 "Payment_norm": "Payment_Method",
12 "Order_norm": "Order_Method",
13 "Location_norm": "Location",
14 "Quantity_Parsed": "Quantity",
15 "Price_Parsed": "Item_Price",
16 "Total_Parsed": "Total_Spent"}
17
18df = df.rename(columns=columns)
19
20df["date"] = df["Datetime_UTC"].dt.date
21df["weekday"] = df["Datetime_UTC"].dt.day_name()
22df["hour"] = df["Datetime_UTC"].dt.hour
23df["month"] = df["Datetime_UTC"].dt.month
24
25campus_locations = {
26 "duke_university",
27 "nc_state",
28 "chapel_hill"
29}
30
31# Create a boolean flag
32df["is_campus"] = df["Location"].isin(campus_locations)
33
34# Create a new categorical column based on the boolean flag - optional, cleaner labels
35df["location_type"] = df["is_campus"].map(
36 {True: "Campus", False: "Non-Campus"}
37)
38
39item_to_category = {
40 # drinks
41 "coffee": "Drinks",
42 "latte": "Drinks",
43 "soda": "Drinks",
44 "smoothie": "Drinks",
45 "juice": "Drinks",
46
47 # food
48 "cake": "Food",
49 "cookie": "Food",
50 "scone": "Food",
51 "salad": "Food",
52 "sandwich": "Food",
53
54 # merchandise
55 "hat": "Merchandise",
56 "mug": "Merchandise",
57 "shirt": "Merchandise",
58}
59df["Item_Category"] = df["Item"].map(item_to_category).fillna("Other")
60
61orders = (
62 df.groupby("Transaction ID", as_index=False)
63 .agg(
64 timestamp=("Datetime_UTC", "min"),
65 total_revenue=("Total_Spent", "sum"),
66 items=("Quantity", "sum"),
67 payment_method=("Payment_Method", "first"),
68 order_method=("Order_Method", "first"),
69 location=("Location", "first"),
70 location_type=("location_type", "first")
71 )
72)
73orders["date"] = orders["timestamp"].dt.date
74orders["weekday"] = orders["timestamp"].dt.day_name()
75orders["hour"] = orders["timestamp"].dt.hour
76
77df.head()
| Transaction ID | Datetime_UTC | Item | Payment_Method | Order_Method | Location | Quantity | Item_Price | Total_Spent | date | weekday | hour | month | is_campus | location_type | Item_Category | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | T100001 | 2021-07-14 15:48:00+00:00 | scone | digital | mobile | cary | 2 | 2.99 | 5.98 | 2021-07-14 | Wednesday | 15.0 | 7.0 | False | Non-Campus | Food |
| 1 | T100001 | 2021-07-14 15:48:00+00:00 | soda | digital | mobile | cary | 4 | 1.85 | 7.40 | 2021-07-14 | Wednesday | 15.0 | 7.0 | False | Non-Campus | Drinks |
| 2 | T100001 | 2021-07-14 15:48:00+00:00 | coffee | digital | mobile | cary | 2 | 2.72 | 5.44 | 2021-07-14 | Wednesday | 15.0 | 7.0 | False | Non-Campus | Drinks |
| 3 | T100002 | 2023-05-30 12:41:00+00:00 | scone | card | in_store | durham | 3 | 2.82 | 8.46 | 2023-05-30 | Tuesday | 12.0 | 5.0 | False | Non-Campus | Food |
| 4 | T100003 | 2021-09-28 19:48:00+00:00 | coffee | card | grub hub | raleigh | 5 | 2.63 | 13.15 | 2021-09-28 | Tuesday | 19.0 | 9.0 | False | Non-Campus | Drinks |
1orders.head()
| Transaction ID | timestamp | total_revenue | items | payment_method | order_method | location | location_type | date | weekday | hour | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | T100001 | 2021-07-14 15:48:00+00:00 | 18.82 | 8 | digital | mobile | cary | Non-Campus | 2021-07-14 | Wednesday | 15.0 |
| 1 | T100002 | 2023-05-30 12:41:00+00:00 | 8.46 | 3 | card | in_store | durham | Non-Campus | 2023-05-30 | Tuesday | 12.0 |
| 2 | T100003 | 2021-09-28 19:48:00+00:00 | 13.15 | 5 | card | grub hub | raleigh | Non-Campus | 2021-09-28 | Tuesday | 19.0 |
| 3 | T100004 | 2023-03-12 17:21:00+00:00 | 42.10 | 2 | digital | in_store | durham | Non-Campus | 2023-03-12 | Sunday | 17.0 |
| 4 | T100005 | 2025-01-16 18:24:55+00:00 | 21.84 | 3 | digital | in_store | nc_state | Campus | 2025-01-16 | Thursday | 18.0 |
Questions About Amounts and Comparisons#
Questions about amounts and comparisons focus on how much and how categories differ. Typical examples include comparing revenue across categories, examining average order totals by group, or identifying which categories contribute most to an overall metric.
As in the Matplotlib chapter, these questions rely on position along a common quantitative scale. The main difference in Seaborn is that many comparison plots can be created directly from a DataFrame, and Seaborn will often aggregate values automatically.
Bar Plots#
Bar plots are the most common way to compare amounts across categories. In Seaborn, bar plots are created using sns.barplot. The most important behavior to understand is that Seaborn aggregates by default when multiple rows map to the same category.
If you want totals, you should aggregate explicitly first (as you did throughout the Matplotlib chapter). If you want a “typical” value (mean/median), Seaborn can compute it directly.
Example A: Total revenue by item category (explicit aggregation)
1#sns.set_theme()
2
3category_totals = (
4 df.groupby("Item_Category", observed=True, as_index=False)
5 .agg(revenue=("Total_Spent", "sum"))
6 .sort_values("revenue", ascending=False)
7)
8
9ax = sns.barplot(
10 data=category_totals,
11 x="Item_Category",
12 y="revenue"
13).set(title="Total Revenue by Item Category", xlabel="Item Category", ylabel="Total Revenue")
14
15plt.show()
Example B: Average item-level spend by payment method (implicit aggregation)
In this example, we use Seaborn’s barplot directly on the item-level data. Because multiple transactions share the same payment method, Seaborn automatically aggregates the data before plotting, allowing us to compare typical spending behavior across payment types with minimal code.
1ax = sns.barplot(
2 data=df,
3 x="Payment_Method",
4 y="Total_Spent"
5)
6
7ax.set_xlabel("Payment Method")
8ax.set_ylabel("Average Item-Level Spend")
9ax.set_title("Average Item-Level Spend by Payment Method")
10plt.show()
By default, Seaborn displays error bars on bar plots when it performs internal aggregation. These error bars represent uncertainty around the estimated mean, typically shown as a confidence interval derived from resampling.
The error bars provide important context: categories with wider intervals indicate greater variability in item-level spending, while narrower intervals suggest more consistent transaction amounts. When the goal is to emphasize average behavior, these intervals can help distinguish meaningful differences from noise.
If uncertainty is not relevant to the question being asked, error bars can be disabled explicitly:
1sns.barplot(data=df, x="Payment_Method", y="Total_Spent", errorbar=None).set(
2 title="Average Item-Level Spend by Payment Method",
3 xlabel="Payment Method",
4 ylabel="Average Item-Level Spend")
5plt.show()
Going back to the initial bar chart, we used explicit aggregation. We can
have Seaborn reprodcuce this, but we’ll need to explicitly tell Seaborn how to
aggregate to use the sum rather than the default mean.
1ax = sns.barplot(
2 data=df,
3 x="Item_Category",
4 y="Total_Spent",
5 estimator=np.sum,
6 errorbar=None
7)
8
9ax.set_title("Total Revenue by Item Category")
10ax.set_xlabel("Item Category")
11ax.set_ylabel("Total Revenue")
12
13plt.show()
What’s happening here
Seaborn groups the data by
Item_CategoryIt applies
np.sumtoTotal_Spentwithin each groupOne bar is drawn per category using the aggregated value
Error bars are disabled because they don’t make sense for totals
Using estimator=np.sum is convenient, but it hides an important step. The aggregation still happens — it’s just implicit instead of explicit*.
Explicit aggregation:
makes assumptions visible
allows inspection and validation
avoids surprises
Use Seaborn’s internal aggregation for quick comparisons, but aggregate explicitly when totals or validation matter.
Dot and Point Plots#
For comparisons involving many categories or when visual simplicity is important, point-based plots can be preferable to bars. Seaborn’s sns.pointplot emphasizes relative position and works well for comparing group-level summaries.
Like barplot, pointplot aggregates by default.
1fig, ax = plt.subplots(figsize=(9, 4))
2sns.pointplot(
3 data=orders,
4 x="order_method",
5 y="total_revenue",
6 ax=ax,
7 errorbar=None,
8 linestyle='none'
9)
10
11ax.set_xlabel("Order Method")
12ax.set_ylabel("Average Order Total")
13ax.set_title("Average Order Total by Order Method")
14
15plt.show()
In the previous plot, order methods are shown in their default order, which makes comparison possible but not especially clear. When comparing magnitudes, it is often more effective to sort categories by the value being plotted.
In the next example, order methods are ordered by their average order total, error bars are reintroduced, and the y-axis is anchored at zero with a consistent upper bound. This produces a more disciplined comparison: while the visual emphasis is reduced, it becomes clear that average order totals across methods are relatively similar rather than dramatically different.
1fig, ax = plt.subplots(figsize=(9, 5))
2ax = sns.pointplot(
3 data=orders,
4 x="order_method",
5 y="total_revenue",
6 order=(
7 orders.groupby("order_method")["total_revenue"]
8 .mean()
9 .sort_values(ascending=False)
10 .index
11 ),
12 #errorbar=None,
13 linestyle='none',
14 ax=ax
15)
16
17ax.set_xlabel("Order Method")
18ax.set_ylabel("Average Order Total")
19ax.set_title("Average Order Total by Order Method")
20ax.set_ylim(bottom=0, top=orders["total_revenue"].mean() * 1.5)
21ax.tick_params(axis="x", rotation=30)
22
23plt.show()
Grouped Bar Charts#
As in the Matplotlib chapter, grouped bar charts are useful for comparing counts across two categorical variables. The underlying analytical work is the same: we must decide what is being counted and at what grain. Seaborn simplifies the plotting step by handling the grouping visually through the hue parameter, rather than requiring a pivoted DataFrame.
Step 1: Aggregate to the correct grain
1grouped = (
2 df.groupby(
3 ["Payment_Method", "Order_Method"],
4 as_index=False,
5 observed=True
6 )
7 .agg(count=("Transaction ID", "nunique"))
8 .sort_values("count", ascending=False)
9)
This step is still explicit. Seaborn does not remove the need to think about what is being counted.
Step 2: Plot grouped bars using hue
1fig, ax = plt.subplots(figsize=(10, 4), layout='constrained')
2
3sns.barplot(
4 data=grouped,
5 x="Payment_Method",
6 y="count",
7 hue="Order_Method",
8 ax=ax
9)
10
11ax.set_xlabel("Payment Method")
12ax.set_ylabel("Number of Transactions")
13ax.set_title("Transaction Counts by Payment and Order Method")
14
15plt.show()
How this compares to the Matplotlib version
The aggregation logic is identical
No pivot table is required
Grouping is expressed declaratively using
hueLegends and bar placement are handled automatically
Conceptually, this answers the same question as the Matplotlib example:
How do transaction counts vary across payment methods, and how does that breakdown differ by order method?
Questions About Change Over Time#
Questions about change over time focus on how a value evolves across a temporal sequence. Before plotting any time series, it is essential to confirm that the data has the expected temporal structure. Missing time periods can distort trends, hide inactivity, or create misleading visual continuity.
For that reason, we begin by addressing gaps in time before introducing line plots and seasonality.
Gaps and Missing Time Periods#
Seaborn assumes that the x-axis represents an ordered sequence, but it does not automatically insert missing time periods. If dates are missing from a daily time series, the plot will connect the surrounding points directly, potentially hiding periods where no activity occurred.
In many operational datasets, such as café sales, missing dates usually indicate zero activity, not missing data. To make this explicit, we must construct a complete sequence of dates and fill missing values before plotting.
Example: Fill missing dates with zeros
1daily_revenue = (
2 df.groupby("date", observed=True, as_index=False)
3 .agg(revenue=("Total_Spent", "sum"))
4)
5
6daily_revenue["date"] = pd.to_datetime(daily_revenue["date"])
7
8full_dates = pd.date_range(
9 start=daily_revenue["date"].min(),
10 end=daily_revenue["date"].max(),
11 freq="D"
12)
13
14daily_revenue_filled = (
15 daily_revenue
16 .set_index("date")
17 .reindex(full_dates, fill_value=0)
18 .rename_axis("date")
19 .reset_index()
20)
This step establishes the correct daily structure and ensures that zero-revenue days are represented explicitly.
Line Plots#
Once the time series has a consistent temporal structure, line plots can be used to examine trends and variation over time. Seaborn’s sns.lineplot is the primary tool for this purpose.
If the data already contains one row per time unit, lineplot behaves similarly to Matplotlib. If multiple rows share the same time value, Seaborn will aggregate internally.
Example: Daily revenue over time (explicit aggregation)
1fig, ax = plt.subplots(figsize=(12, 4), layout='constrained')
2sns.lineplot(
3 data=daily_revenue_filled,
4 x="date",
5 y="revenue",
6 errorbar=None,
7 ax=ax
8)
9
10ax.set_xlabel("Date")
11ax.set_ylabel("Daily Revenue")
12ax.set_title("Daily Revenue Over Time")
13
14plt.show()
This plot shows overall trends while preserving periods of inactivity.
Seasonality and Temporal Alignment#
Some time-based questions focus on recurring patterns rather than long-term trends. Seasonality analysis aligns observations within a repeating cycle (such as a calendar year) so that patterns can be compared across years.
To do this, we derive two fields from the date:
yearto separate observationsday_of_yearto align the seasonal cycle
Example: Seasonality view by year
1daily_revenue_filled["year"] = daily_revenue_filled["date"].dt.year
2daily_revenue_filled["day_of_year"] = daily_revenue_filled["date"].dt.dayofyear
3
4fig, ax = plt.subplots(figsize=(12, 4), layout='constrained')
5sns.lineplot(
6 data=daily_revenue_filled,
7 x="day_of_year",
8 y="revenue",
9 hue="year",
10 alpha=0.6,
11 errorbar=None,
12 ax=ax
13)
14
15ax.set_xlabel("Day of Year")
16ax.set_ylabel("Daily Revenue")
17ax.set_title("Daily Revenue by Year (Seasonality View)")
18
19month_starts = pd.date_range("2021-01-01", periods=12, freq="MS").dayofyear
20month_labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
21 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
22
23ax.set_xticks(month_starts)
24ax.set_xticklabels(month_labels)
25
26plt.show()
This alignment makes it easier to compare the shape of revenue patterns across years.
Grouped seasonality#
Seasonal patterns may differ across groups. For example, campus locations may follow the academic calendar, while non-campus locations may exhibit steadier demand.
1daily_loc = (
2 df.groupby(["date", "location_type"], observed=True, as_index=False)
3 .agg(revenue=("Total_Spent", "sum"))
4)
5
6daily_loc["date"] = pd.to_datetime(daily_loc["date"])
7daily_loc["day_of_year"] = daily_loc["date"].dt.dayofyear
8
9seasonality_loc = (
10 daily_loc.groupby(["location_type", "day_of_year"], observed=True, as_index=False)
11 .agg(avg_revenue=("revenue", "mean"))
12)
13
14fig, ax = plt.subplots(figsize=(12, 4), layout='constrained')
15sns.lineplot(
16 data=seasonality_loc,
17 x="day_of_year",
18 y="avg_revenue",
19 hue="location_type",
20 errorbar=None,
21 ax=ax
22)
23
24ax.set_xlabel("Day of Year")
25ax.set_ylabel("Average Daily Revenue")
26ax.set_title("Seasonality of Daily Revenue by Location Type")
27
28ax.set_xticks(month_starts)
29ax.set_xticklabels(month_labels)
30
31plt.show()
Questions About Distributions#
Questions about distributions focus on variability, spread, skewness, and extreme values, rather than individual observations or trends over time. These questions help answer whether values are typical or unusual, how consistent behavior is, and whether averages are representative.
Seaborn is particularly well suited for distributional analysis because it provides high-level plots that combine summary statistics and density information with minimal configuration. As in earlier sections, the key is to understand what each plot emphasizes and what it hides.
Histograms and KDEs#
Histograms are often the first tool used to examine a distribution. Seaborn’s sns.histplot extends Matplotlib’s histogram by making it easy to switch between counts and densities, and to optionally overlay a kernel density estimate (KDE).
Example: Distribution of transaction totals (count-based histogram)
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.histplot(
4 data=orders,
5 x="total_revenue",
6 bins=30,
7 ax=ax
8)
9
10ax.set_xlabel("Transaction Total")
11ax.set_ylabel("Count")
12ax.set_title("Distribution of Transaction Totals")
13
14plt.show()
This view emphasizes how frequently different transaction sizes occur. As expected for café data, the distribution is strongly right-skewed: most transactions are small, with a long tail of larger purchases.
Density vs count#
By default, histograms show counts. In some cases, especially when comparing distributions across groups, it can be useful to normalize the histogram so that the area sums to one.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.histplot(
4 data=orders,
5 x="total_revenue",
6 bins=30,
7 stat="density",
8 ax=ax
9)
10
11ax.set_xlabel("Transaction Total")
12ax.set_ylabel("Density")
13ax.set_title("Distribution of Transaction Totals (Density)")
14
15plt.show()
Density-based histograms emphasize shape rather than absolute frequency.
KDE overlays: when they help and when they mislead#
Seaborn makes it easy to overlay a KDE on top of a histogram:
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.histplot(
4 data=orders,
5 x="total_revenue",
6 bins=30,
7 kde=True,
8 ax=ax
9)
10
11ax.set_xlabel("Transaction Total")
12ax.set_ylabel("Density")
13ax.set_title("Transaction Totals with KDE Overlay")
14
15plt.show()
KDEs can help reveal the overall shape of a distribution, especially when the sample size is large. However, they can also smooth away important features or suggest structure that is not truly present. KDEs are best treated as exploratory aids rather than precise summaries.
Box Plots#
Box plots provide a compact summary of a distribution using quartiles and extreme values. They are especially useful for comparing distributions across categories.
Example: Distribution of order totals by payment method
1fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
2
3sns.boxplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 ax=ax
8)
9
10ax.set_xlabel("Payment Method")
11ax.set_ylabel("Order Total")
12ax.set_title("Distribution of Order Totals by Payment Method")
13
14plt.show()
Box plots highlight differences in medians, spread, and the presence of outliers, but they do not show how values are clustered within those ranges.
Grouped box plots using hue#
Additional grouping can be introduced using hue:
1fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
2
3sns.boxplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 hue="location_type",
8 ax=ax
9)
10
11ax.set_xlabel("Payment Method")
12ax.set_ylabel("Order Total")
13ax.set_title("Order Totals by Payment Method and Location Type")
14
15plt.show()
Grouped box plots are effective when the number of groups is small and comparisons are meaningful.
Violin and Hybrid Plots#
Violin plots extend box plots by showing the full distribution shape using a smoothed density estimate. They are particularly useful when understanding where values are concentrated matters.
Example: Violin plot of order totals by payment method
1fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
2
3sns.violinplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 ax=ax
8)
9
10ax.set_xlabel("Payment Method")
11ax.set_ylabel("Order Total")
12ax.set_title("Distribution of Order Totals by Payment Method")
13
14plt.show()
Violin plots reveal multimodality and clustering that box plots hide, but they rely on KDE smoothing and should be interpreted with care.
Split violins for grouped distributions#
When comparing two groups, split violins can be effective:
1fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
2
3sns.violinplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 hue="location_type",
8 split=True,
9 ax=ax
10)
11
12ax.set_xlabel("Payment Method")
13ax.set_ylabel("Order Total")
14ax.set_title("Order Totals by Payment Method and Location Type")
15
16plt.show()
Split violins show distribution shape but not group size, so similar-looking violins may represent very different numbers of observations.
As you can see below, campus-based locations have a much smaller number of cash transactions.
1loc_pay_counts = (
2 orders.groupby(["location_type", "payment_method"], observed=True)
3 .size()
4 .reset_index(name="count")
5 .sort_values("count", ascending=False)
6)
7
8loc_pay_counts
| location_type | payment_method | count | |
|---|---|---|---|
| 4 | Non-Campus | card | 20767 |
| 0 | Campus | card | 14349 |
| 6 | Non-Campus | digital | 14303 |
| 2 | Campus | digital | 10042 |
| 5 | Non-Campus | cash | 7199 |
| 1 | Campus | cash | 1123 |
| 7 | Non-Campus | other | 1121 |
| 3 | Campus | other | 676 |
Box + violin combinations#
To combine summary statistics with distribution shape, Seaborn allows overlaying box plots on violins:
1fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
2
3sns.violinplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 inner=None,
8 ax=ax
9)
10
11sns.boxplot(
12 data=orders,
13 x="payment_method",
14 y="total_revenue",
15 width=0.2,
16 ax=ax
17)
18
19ax.set_xlabel("Payment Method")
20ax.set_ylabel("Order Total")
21ax.set_title("Order Totals by Payment Method (Box + Violin)")
22
23plt.show()
This hybrid view balances statistical summary and distribution detail, but should be used sparingly to avoid visual clutter.
Key takeaway#
Different distribution plots emphasize different aspects of the data. Histograms reveal overall shape, box plots summarize spread and outliers, and violin plots expose density and clustering. Choosing among them depends on whether the goal is summary, comparison, or exploration.
Questions About Relationships Between Variables#
Questions about relationships focus on how two or more variables move together. Rather than asking how much or how often, these questions ask whether changes in one variable are associated with changes in another, and whether those associations are consistent, noisy, or conditional on context.
Seaborn provides several tools for relationship analysis that build directly on scatter plots, adding statistical summaries and distributional context while keeping the underlying data visible.
Scatter Plots#
Scatter plots are the primary tool for examining relationships between two quantitative variables. In Seaborn, sns.scatterplot provides a higher-level interface that supports transparency and additional encodings with minimal configuration.
Example: Number of items vs total order revenue
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.scatterplot(
4 data=orders,
5 x="items",
6 y="total_revenue",
7 alpha=0.3,
8 ax=ax
9)
10
11ax.set_xlabel("Number of Items")
12ax.set_ylabel("Total Order Revenue")
13ax.set_title("Order Size vs Total Revenue")
14
15plt.show()
This plot shows a clear positive relationship: larger orders generally result in higher total revenue, though there is substantial variability.
Overplotting and transparency#
When many observations overlap, points can obscure one another. Transparency (alpha) helps reveal areas of high density and prevents dense regions from appearing artificially sparse.
Multiple encodings with hue and size#
Seaborn allows additional variables to be encoded directly in the plot.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.scatterplot(
4 data=orders,
5 x="items",
6 y="total_revenue",
7 hue="location_type",
8 alpha=0.4,
9 ax=ax
10)
11
12ax.set_xlabel("Number of Items")
13ax.set_ylabel("Total Order Revenue")
14ax.set_title("Order Size vs Revenue by Location Type")
15
16plt.show()
Additional encodings should be used sparingly. Each added variable increases cognitive load and should answer a clear analytical question.
Joint Distributions of Two Variables#
Scatter plots show relationships but hide how each variable is distributed individually. Seaborn’s jointplot combines a scatter plot with marginal distributions, providing context on both dimensions simultaneously.
Example: Items vs total revenue with marginal distributions
1sns.jointplot(
2 data=orders,
3 x="items",
4 y="total_revenue",
5 kind="scatter",
6 height=5
7)
8plt.show()
The central panel shows the relationship, while the marginal plots reveal how frequently different values occur.
KDE vs histogram marginals#
By default, jointplot uses histograms for the marginals. KDE-based marginals can be enabled:
1sns.jointplot(
2 data=orders,
3 x="items",
4 y="total_revenue",
5 kind="kde",
6 height=5
7)
8plt.show()
KDE-based joint plots emphasize overall structure but may smooth away important details, especially when data is sparse or highly skewed. They are best used for exploratory pattern recognition rather than precise interpretation.
When joint plots are appropriate#
Joint plots are most useful when:
examining a single, important relationship
understanding both association and marginal distributions
exploring data early in an analysis
They are less suitable for comparisons across many groups or for presentation-ready figures.
Trend Lines and Relationship Summaries#
In some cases, it is useful to summarize a relationship with a trend line. Seaborn provides functions that overlay simple statistical models on scatter plots.
Example: Scatter plot with regression line
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.regplot(
4 data=orders,
5 x="items",
6 y="total_revenue",
7 scatter_kws={"alpha": 0.3},
8 ax=ax
9)
10
11ax.set_xlabel("Number of Items")
12ax.set_ylabel("Total Order Revenue")
13ax.set_title("Order Size vs Revenue with Trend Line")
14
15plt.show()
The regression line highlights the overall direction of the relationship but should not be interpreted as a predictive model.
Comparing relationships across groups with lmplot#
When the relationship itself may differ across categories, lmplot provides a convenient way to compare trends.
1sns.lmplot(
2 data=orders,
3 x="items",
4 y="total_revenue",
5 hue="location_type",
6 height=4,
7 aspect=1.5,
8 scatter_kws={"alpha": 0.3}
9)
10plt.show()
This plot makes it easier to see whether the strength or slope of the relationship varies across groups.
Visual summaries vs predictive models#
Trend lines in Seaborn are descriptive, not inferential. They summarize patterns in the data but do not replace formal modeling, validation, or causal analysis.
Exploring Many Relationships at Once#
When working with multiple quantitative variables, it can be helpful to scan for relationships before deciding which ones deserve deeper analysis. Seaborn’s pairplot provides a compact overview of many pairwise relationships at once.
Example: Pairwise relationships among numeric variables
1sns.pairplot(
2 orders[["items", "total_revenue", "hour"]],
3 height=2.5
4)
5plt.show()
The diagonal shows univariate distributions, while off-diagonal plots show pairwise relationships.
Using hue in pair plots#
1sns.pairplot(
2 orders[["items", "total_revenue", "hour", "location_type"]],
3 hue="location_type",
4 height=2.5
5)
6plt.show()
Coloring by group can reveal whether relationships differ across categories, but it also increases visual complexity.
Scalability and limitations#
Pair plots scale poorly as the number of variables increases. They are best used as reconnaissance tools early in analysis, not as final explanatory graphics.
Key takeaway#
Scatter plots form the foundation of relationship analysis. Seaborn extends them with marginal distributions, trend summaries, and multi-variable overviews, making it easier to explore relationships quickly. As with all visualization, the goal is insight—not decoration—and each added layer should serve a clear analytical purpose.
Questions About Composition and Proportion#
Questions about composition focus on how a whole is divided into parts. Rather than asking how much or how values change, these questions ask what contributes to an overall total and how those contributions differ across groups.
Typical examples include:
How revenue is split across product categories
How payment methods contribute within different locations
Whether the composition of activity changes by time or context
In Seaborn, composition questions are most effectively answered using grouped bar charts, sometimes combined with normalization to emphasize proportions rather than raw totals.
Grouped Composition#
Grouped bar charts allow composition to be examined across categories by introducing a secondary grouping variable using hue. Each bar represents a total, and the grouping shows how those totals are divided.
As in earlier sections, the analytical work happens before plotting: deciding what to aggregate and at what grain.
Example: Revenue composition by item category and location type
1category_loc = (
2 df.groupby(["Item_Category", "location_type"], observed=True, as_index=False)
3 .agg(revenue=("Total_Spent", "sum"))
4)
5
6fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
7
8sns.barplot(
9 data=category_loc,
10 x="Item_Category",
11 y="revenue",
12 hue="location_type",
13 ax=ax
14)
15
16ax.set_xlabel("Item Category")
17ax.set_ylabel("Total Revenue")
18ax.set_title("Revenue by Item Category and Location Type")
19
20plt.show()
This plot shows how total revenue varies by item category, while also revealing differences between campus and non-campus locations.
Category ordering#
By default, Seaborn preserves the order in which categories appear in the data. For composition plots, ordering categories by total contribution often improves readability.
1category_order = (
2 category_loc.groupby("Item_Category")["revenue"]
3 .sum()
4 .sort_values(ascending=False)
5 .index
6)
7
8fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
9
10sns.barplot(
11 data=category_loc,
12 x="Item_Category",
13 y="revenue",
14 hue="location_type",
15 order=category_order,
16 ax=ax
17)
18
19ax.set_xlabel("Item Category")
20ax.set_ylabel("Total Revenue")
21ax.set_title("Revenue by Item Category and Location Type")
22
23plt.show()
Ordering is an analytical decision. It determines which comparisons are emphasized and should reflect the question being asked.
Interpreting relative contributions#
Grouped bar charts support comparison, but they require careful interpretation. Differences in bar height reflect total contribution, while differences within groups reflect how composition varies across categories. When totals differ greatly, relative composition can be harder to see.
This motivates the use of normalized views.
Normalized (100%) Views#
In some cases, the total size of each group is less important than how each group is composed. Normalized bar charts rescale each group so that it sums to 100%, emphasizing proportions rather than absolute values.
Seaborn does not normalize automatically, so this step must be done explicitly.
Example: Proportional revenue composition by item category and location type
1category_loc_prop = (
2 category_loc
3 .assign(total=lambda d: d.groupby("location_type")["revenue"].transform("sum"))
4 .assign(prop=lambda d: d["revenue"] / d["total"])
5)
6
7fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
8
9sns.barplot(
10 data=category_loc_prop,
11 x="Item_Category",
12 y="prop",
13 hue="location_type",
14 order=category_order,
15 ax=ax
16)
17
18ax.set_xlabel("Item Category")
19ax.set_ylabel("Proportion of Revenue")
20ax.set_title("Proportional Revenue Composition by Location Type")
21
22plt.show()
This view makes differences in composition clearer, even when total revenue differs substantially between groups.
When proportions matter more than totals#
Normalized views are most useful when:
Comparing composition across groups of different sizes
The focus is on relative contribution rather than volume
Absolute differences would dominate the visual otherwise
They are less appropriate when total magnitude is itself important.
Here is a revised version of Section 8.3 that cleanly incorporates both pie charts and stacked bar charts, framing them as deliberate design choices rather than missing features. This drops directly into the section you just wrote.
De-Emphasized Chart Types#
Pie charts and stacked bar charts are commonly used to show composition, but both make comparisons more difficult than they appear. In each case, parts of a whole do not share a common baseline, which makes it hard to judge relative sizes accurately.
Pie charts require viewers to compare angles and areas, which are perceptually weaker than comparing lengths along a shared axis. They also scale poorly as the number of categories increases and become cluttered or ambiguous when values are similar.
Stacked bar charts present a related problem. While they show how totals are composed, only the first segment in each stack shares a common baseline. All other segments float above it, making comparisons across groups difficult. As a result, stacked bars are better at showing accumulation than comparison.
For these reasons, Seaborn emphasizes grouped bar charts and normalized (100%) bar charts, which place values along a shared axis and make differences easier to interpret. When stacking is genuinely necessary—for example, to show composition over time—it is often clearer to construct stacked bars explicitly using Matplotlib after reshaping the data.
This design choice reinforces a broader principle introduced earlier: composition is best communicated through aligned comparisons, not through isolated slices or floating segments.
Key takeaway#
Composition questions are about parts of a whole. Grouped bar charts show how those parts contribute in absolute terms, while normalized views emphasize relative contribution. Choosing between them depends on whether totals or proportions matter more for the question at hand.
Faceting as a First-Class Concept#
As datasets grow more complex, a single plot often cannot support all necessary comparisons without becoming cluttered. Adding color, shape, or size can help, but these encodings scale poorly as the number of groups increases. At some point, the plot becomes difficult to read, and important patterns are lost.
Seaborn addresses this problem through faceting, which creates multiple small plots that share the same structure but show different subsets of the data. This approach—often called small multiples—makes comparisons easier by repeating the same visual grammar across panels.
The key idea is simple:
Faceting scales comparisons better than color alone.
Seaborn’s FacetGrid is the foundation for faceted plots. It defines a grid of subplots based on one or more categorical variables and then maps a plotting function onto each subset of the data.
At a high level, faceting separates concerns:
the grid defines how the data is split
the plotting function defines how each subset is visualized
Faceting vs grouping with color#
Grouping with color (hue) works well when:
there are few groups
the groups are visually distinct
comparisons are simple
As the number of groups increases, color becomes harder to interpret. Faceting avoids this problem by giving each group its own panel while keeping axes aligned.
Example: Faceting distributions by location type
Instead of overlaying distributions with color, we can facet them:
1g = sns.FacetGrid(
2 orders,
3 col="location_type",
4 height=4,
5 aspect=1.2
6)
7
8g.map_dataframe(
9 sns.histplot,
10 x="total_revenue",
11 bins=30
12)
13
14g.set_axis_labels("Order Total", "Count")
15g.set_titles(col_template="{col_name}")
16
17plt.show()
Each panel shows the same distribution structure, making it easier to compare shapes and spread without relying on color.
Small multiples for comparison#
Faceting works because:
each panel uses the same scales
patterns repeat visually
differences stand out naturally
This makes small multiples especially effective for identifying subtle differences that would be obscured in a single, crowded plot.
Faceting across categories#
Faceting is often used to compare categorical groups.
1g = sns.FacetGrid(
2 orders,
3 col="payment_method",
4 col_wrap=4,
5 height=3
6)
7
8g.map_dataframe(
9 sns.boxplot,
10 y="total_revenue" # Note, switch between x and y to see the difference.
11)
12
13g.set_axis_labels("Order Total", "")
14g.set_titles(col_template="{col_name}")
15
16plt.show()
In Seaborn, axis orientation is controlled by which variable is assigned to x or y.
Faceting across time#
Faceting can also be used to compare patterns across time periods.
1daily_revenue_filled["year"] = daily_revenue_filled["date"].dt.year
2
3g = sns.FacetGrid(
4 daily_revenue_filled,
5 col="year",
6 col_wrap=3,
7 height=3,
8 aspect=1.3
9)
10
11g.map_dataframe(
12 sns.lineplot,
13 x="date",
14 y="revenue",
15 errorbar=None
16)
17
18g.set_axis_labels("Date", "Daily Revenue")
19g.set_titles(col_template="{col_name}")
20
21plt.show()
Faceting relationships#
Faceting is particularly powerful for relationship plots, where overlapping trends can quickly become unreadable.
1g = sns.FacetGrid(
2 orders,
3 col="location_type",
4 height=4,
5 aspect=1.2
6)
7
8g.map_dataframe(
9 sns.scatterplot,
10 x="items",
11 y="total_revenue",
12 alpha=0.3
13)
14
15g.set_axis_labels("Number of Items", "Total Revenue")
16g.set_titles(col_template="{col_name}")
17
18plt.show()
When to facet#
Faceting is most effective when:
the same plot structure applies to all groups
comparisons across groups are important
adding more colors would reduce clarity
It is less appropriate when:
groups are numerous and panels would become too small
direct comparison within a single axis is required
Faceting turns complexity into structure. By repeating the same visual grammar across aligned panels, Seaborn makes it possible to scale comparisons beyond what color and symbols alone can support. When comparisons start to feel crowded, faceting is often the clearest next step.
Minimal Customization and When to Drop to Matplotlib#
Seaborn is designed to make common analytical plots easy to produce and easy to read. Its defaults handle many decisions automatically—colors, spacing, aggregation, and legends—allowing you to focus on the structure of the data rather than the mechanics of drawing.
At the same time, Seaborn is not intended to replace Matplotlib. It is built on top of it. Understanding where Seaborn’s abstractions help, and where they begin to limit control, is an important part of using the library effectively.
The goal of this section is not to encourage heavy customization, but to show how a small amount of deliberate adjustment can improve clarity—and when it is more appropriate to work directly with Matplotlib instead.
Minimal, High-Impact Customization#
Most Seaborn plots can be improved with a few simple, consistent adjustments. These changes focus on clarity, not appearance.
Common examples include:
Setting clear axis labels
Adding concise titles
Choosing an appropriate figure size
Ensuring layouts do not clip labels or legends
1fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
2
3sns.barplot(
4 data=df,
5 x="Item_Category",
6 y="Total_Spent",
7 errorbar=None,
8 ax=ax
9)
10
11ax.set_xlabel("Item Category")
12ax.set_ylabel("Average Item-Level Spend")
13ax.set_title("Average Item-Level Spend by Item Category")
14
15plt.show()
These adjustments do not change what is being plotted, but they make the plot easier to interpret and less dependent on context.
As a general rule, if a customization does not make the plot clearer or more honest, it is usually unnecessary.
Mixing Seaborn and Matplotlib#
Although Seaborn creates the visual structure of a plot, it does not manage figures or axes on its own. Instead, every Seaborn plotting function ultimately draws onto a Matplotlib Axes object and returns it. This design allows Seaborn plots to be customized using standard Matplotlib commands.
There are two common ways this interaction occurs: explicitly creating an Axes object ahead of time, or letting Seaborn create one automatically.
Explicit axes creation (recommended pattern)#
In most examples in this chapter, we create a figure and axes first using plt.subplots and then pass the axes to Seaborn. This makes it clear where the plot is being drawn and gives full control over layout and sizing.
1fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
2
3sns.barplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 errorbar=None,
8 ax=ax
9)
10
11ax.set_ylim(bottom=0)
12ax.set_xlabel("Payment Method")
13ax.set_ylabel("Average Order Total")
14ax.set_title("Average Order Total by Payment Method")
15
16plt.show()
Here, Seaborn draws onto the ax that was explicitly created, and returns the same Axes object. All subsequent customization happens through Matplotlib.
Letting Seaborn create the axes (optional shortcut)#
If no axes are provided, Seaborn will create one automatically and return it.
1ax = sns.barplot(
2 data=orders,
3 x="payment_method",
4 y="total_revenue",
5 errorbar=None
6)
7
8ax.set_ylim(bottom=0)
9ax.set_xlabel("Payment Method")
10ax.set_ylabel("Average Order Total")
11ax.set_title("Average Order Total by Payment Method")
12
13plt.show()
This approach is convenient for quick exploration, but the axes creation is implicit. For more complex layouts and sizing, explicitly creating axes is the better approach
Understanding where the Axes object comes from clarifies several important ideas:
Seaborn does not replace Matplotlib; it builds on it
Matplotlib controls layout, limits, and annotations
Passing
ax=is optional, but recommended for clarityCustomization always happens through the returned
Axes
Seaborn draws the plot, Matplotlib owns the axes.
Once that relationship is clear, mixing the two libraries becomes natural rather than confusing, and “dropping down” to Matplotlib feels like a continuation of the same workflow rather than a switch in tools.
When Seaborn’s Abstractions Become Limiting#
Seaborn works best when the plot fits its statistical model: tidy data, clear groupings, and standard comparisons. When those assumptions no longer hold, Seaborn can become awkward to use.
Common signs that it may be time to drop to Matplotlib include:
Needing precise control over bar placement or stacking
Building complex multi-axis or multi-layer layouts
Creating diagrams or non-statistical graphics
Repeatedly working around the API rather than with it
For example, stacked bar charts require explicit control over cumulative positioning and are more naturally expressed in Matplotlib after reshaping the data.
This is not a failure of Seaborn. It reflects a design choice: Seaborn prioritizes comparison and statistical clarity over geometric flexibility.
A Practical Decision Guide#
A simple way to decide which tool to use:
Is this a standard statistical comparison or distribution? → Use Seaborn
Do I need explicit control over geometry or layout? → Use Matplotlib
Am I fighting defaults or writing workarounds? → Switch tools
Switching between Seaborn and Matplotlib is normal and expected. The two libraries are designed to work together.
Closing perspective#
Minimal customization keeps plots readable and reproducible. Knowing when to step outside Seaborn’s abstractions prevents frustration and encourages intentional design.
With this foundation in place, we are better prepared to examine whether plots are not only well constructed, but also trustworthy. The next section focuses on validation and sanity checks—using visualization as a way to confirm assumptions rather than simply display results.
Validation and Sanity Checks#
Visualization is often treated as the final step of analysis, but in practice it should also serve as an ongoing validation tool. Before a plot is used to support interpretation or communication, it is essential to confirm that the data and assumptions behind it are sound.
This section focuses on using visualizations to check, not just to explain. High-level libraries like Seaborn make it easy to produce polished plots quickly, but that convenience can obscure important details such as implicit aggregation, uneven group sizes, missing time periods, or misleading axis choices.
A good plot can still be wrong if the data or assumptions behind it are wrong.
Validation and sanity checks help answer questions such as:
Is the data at the grain I think it is?
Am I aggregating in a way that matches the question?
Are apparent patterns driven by a few extreme values or by many observations?
Do axis limits and encodings exaggerate or hide differences?
The goal of this section is not to introduce new plot types, but to develop analytical discipline. By reusing familiar visualizations and pairing them with simple checks, you can catch errors early, avoid overinterpretation, and build confidence in your conclusions.
These practices are especially important in exploratory analysis, where plots evolve rapidly and assumptions change. The habits introduced here form a bridge between visualization and the broader exploratory data analysis workflow introduced in the next chapter.
Note: This section largely repeats questions presented earlier in this chapter, but you should still review this material to ensure you are performing the appropriate validations as you create visualizations.
Validate the Shape and Grain of the Data#
Before interpreting any visualization, it is important to confirm that the data has the expected shape and grain. Grain refers to what a single row represents: an item, an order, a day, or some other unit of analysis. Many visualization errors occur not because the plot is wrong, but because the data being plotted is at a different level than the analyst assumes.
High-level plotting libraries make it easy to draw a chart from almost any DataFrame. That flexibility increases the importance of checking that each row represents the unit you intend to analyze.
Example 1: Item-level vs order-level data
Consider a scatter plot intended to show the relationship between order size and total revenue. This relationship only makes sense at the order level, where each row corresponds to one transaction.
If item-level data is used accidentally, each order may appear multiple times, once for each item, distorting the relationship.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.scatterplot(
4 data=df, # item-level data
5 x="Quantity",
6 y="Total_Spent",
7 alpha=0.3,
8 ax=ax
9)
10
11ax.set_title("Item-Level View: Quantity vs Total Spent")
12plt.show()
This plot may appear reasonable, but it does not represent the intended relationship. Each point reflects an item, not a full order, and larger orders are overrepresented.
A simple validation check is to count rows per transaction:
1df.groupby("Transaction ID").size().describe()
count 70075.000000
mean 1.427042
std 0.782382
min 1.000000
25% 1.000000
50% 1.000000
75% 2.000000
max 9.000000
dtype: float64
If transactions can have multiple rows, the data is not at the correct grain.
The correct approach is to use the order-level dataset:
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.scatterplot(
4 data=orders, # order-level data
5 x="items",
6 y="total_revenue",
7 alpha=0.3,
8 ax=ax
9)
10
11ax.set_title("Order-Level View: Items vs Total Revenue")
12plt.show()
This plot aligns with the analytical question because each point represents a single order.
Example 2: Time series at the wrong frequency
Time series plots are especially sensitive to grain. A line plot labeled “daily revenue” should have exactly one row per day. If the data is actually item-level or order-level, Seaborn will aggregate implicitly, and it may not be obvious what is being plotted.
1fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
2
3sns.lineplot(
4 data=df,
5 x="date",
6 y="Total_Spent",
7 ax=ax
8)
9
10ax.set_title("Implicit Aggregation from Item-Level Data")
11plt.show()
This plot hides the fact that many rows contribute to each point on the line.
A simple shape check helps validate the intended grain:
1df.groupby("date").size().describe()
count 1823.000000
mean 52.934174
std 15.527605
min 1.000000
25% 42.000000
50% 54.000000
75% 64.000000
max 104.000000
dtype: float64
If most dates have many rows, the data must be aggregated explicitly before plotting.
1daily_revenue = (
2 df.groupby("date", observed=True, as_index=False)
3 .agg(revenue=("Total_Spent", "sum"))
4)
5
6fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
7
8sns.lineplot(
9 data=daily_revenue,
10 x="date",
11 y="revenue",
12 errorbar=None,
13 ax=ax
14)
15
16ax.set_title("Explicit Daily Revenue")
17plt.show()
This version makes the data shape explicit and avoids relying on Seaborn’s internal aggregation.
Practical takeaway#
Before trusting a visualization, pause and ask:
What does one row represent?
How many rows contribute to each plotted element?
Is any aggregation happening implicitly?
Answering these questions early prevents subtle but serious misinterpretations later in the analysis.
Validate Aggregation Assumptions#
Many visualizations rely on aggregation: totals, averages, or counts that summarize multiple observations. Aggregation is not inherently problematic, but it introduces assumptions that should be checked explicitly. When those assumptions are left unexamined, plots can communicate a misleading sense of precision or importance.
Seaborn makes aggregation easy—sometimes too easy. Several plot types compute summary statistics automatically, which can blur the line between raw data and derived values. Validating aggregation assumptions ensures that the summary being shown actually answers the intended question.
Example 1: Implicit vs explicit means in bar plots
A common use of bar plots is to compare average values across categories. By default, sns.barplot computes the mean of the y-variable for each category.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.barplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 ax=ax
8)
9
10ax.set_title("Implicit Mean Order Total by Payment Method")
11plt.show()
This plot shows average order totals, but the aggregation is implicit. To validate what is being plotted, compute the same summary explicitly:
1orders.groupby("payment_method")["total_revenue"].mean()
payment_method
card 22.153033
cash 14.851679
digital 20.493441
other 19.434318
Name: total_revenue, dtype: float64
If the numbers match the visual ordering and scale, the aggregation assumption is correct. If not, the plot may be answering a different question than expected.
Making aggregation explicit can also clarify intent: (note the explicity sorting as well)
1summary = (
2 orders.groupby("payment_method", observed=True, as_index=False)
3 .agg(avg_total=("total_revenue", "mean")).sort_values("avg_total", ascending=False)
4)
5
6fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
7
8sns.barplot(
9 data=summary,
10 x="payment_method",
11 y="avg_total",
12 ax=ax
13)
14
15ax.set_title("Explicit Mean Order Total by Payment Method")
16plt.show()
Both plots may look identical, but the second makes the aggregation decision visible and inspectable.
Example 2: Means vs totals in composition questions
Aggregation assumptions also matter when examining composition. Consider a bar plot intended to show which item categories contribute the most revenue.
If means are plotted instead of totals, the interpretation changes completely.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.barplot(
4 data=df,
5 x="Item_Category",
6 y="Total_Spent",
7 ax=ax
8)
9
10ax.set_title("Implicit Mean Item-Level Spend by Category")
11plt.show()
This plot answers a different question than many readers expect: it shows the average spend per item, not total contribution. Additionally, note that misleading y-axis label contributes to the comprehension issues.
A simple validation step is to compute totals explicitly and compare:
1category_totals = (
2 df.groupby("Item_Category", observed=True, as_index=False)
3 .agg(revenue=("Total_Spent", "sum"))
4)
5category_totals
| Item_Category | revenue | |
|---|---|---|
| 0 | Drinks | 637373.35 |
| 1 | Food | 489228.70 |
| 2 | Merchandise | 302809.33 |
| 3 | Other | 13004.54 |
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.barplot(
4 data=category_totals,
5 x="Item_Category",
6 y="revenue",
7 ax=ax
8)
9
10ax.set_title("Total Revenue by Item Category")
11plt.show()
The difference between these two plots highlights how aggregation choices shape interpretation.
Practical takeaway#
Before interpreting an aggregated plot, confirm:
Which statistic is being computed
Whether the aggregation is implicit or explicit
Whether the statistic matches the analytical question
When in doubt, compute summaries directly and compare them to what the plot appears to show. Explicit aggregation reduces ambiguity and makes analytical assumptions easier to validate.
Validate Time Structure#
Time-based visualizations rely on an implicit assumption: that the time axis accurately reflects both when observations occurred and when nothing happened. If this structure is incorrect, line plots and trends can appear smoother, more continuous, or more stable than the underlying data actually is.
Validating time structure means confirming that timestamps are correctly parsed, time units are consistent, and missing periods are handled intentionally rather than ignored.
Example 1: Detecting missing time periods
A common issue in time series data is the presence of gaps. When days or hours are missing, line plots will connect the surrounding points, potentially hiding periods of inactivity.
1daily_revenue = (
2 df.groupby("date", observed=True, as_index=False)
3 .agg(revenue=("Total_Spent", "sum"))
4)
5
6fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
7
8sns.lineplot(
9 data=daily_revenue,
10 x="date",
11 y="revenue",
12 errorbar=None,
13 ax=ax
14)
15
16ax.set_title("Daily Revenue with Potential Gaps")
17plt.show()
This plot assumes continuity, but it does not reveal whether all dates are present.
A simple validation check is to inspect the spacing between dates:
1daily_revenue["date"] = pd.to_datetime(daily_revenue["date"])
2daily_revenue["date_diff"] = daily_revenue["date"].diff()
3
4daily_revenue["date_diff"].value_counts()
date_diff
1 days 1819
2 days 2
3 days 1
Name: count, dtype: int64
If the expected difference (for example, one day) does not dominate, gaps are likely present.
Example 2: Explicitly filling missing periods
Once gaps are identified, the next step is to decide what they mean. In many operational datasets, missing dates represent zero activity, not missing data.
1full_dates = pd.date_range(
2 start=daily_revenue["date"].min(),
3 end=daily_revenue["date"].max(),
4 freq="D"
5)
6
7daily_revenue_filled = (
8 daily_revenue
9 .set_index("date")
10 .reindex(full_dates, fill_value=0)
11 .rename_axis("date")
12 .reset_index()
13)
Plotting the filled series reveals the true structure of the time series:
1fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
2
3sns.lineplot(
4 data=daily_revenue_filled,
5 x="date",
6 y="revenue",
7 errorbar=None,
8 ax=ax
9)
10
11ax.set_title("Daily Revenue with Missing Dates Filled")
12plt.show()
Periods of inactivity are now visible, and apparent trends are less likely to be artifacts of missing data.
Additional time structure checks#
Beyond gaps, it is useful to validate:
That timestamps are in the expected timezone
That time units (hour, day, month) were derived correctly
That aggregation frequency matches the question being asked
Simple summaries such as counts per time unit or histograms of timestamps can reveal misalignments early.
The timezone definitely needs to be taken into account for certain questions as the datetime field assumes UTC while the cafés are located in the Eastern timezone.
Practical takeaway#
Before interpreting any time-based plot, confirm that:
Time is continuous where it should be
Missing periods are handled intentionally
Aggregation frequency matches the analytical question
Validating time structure ensures that trends reflect real behavior rather than artifacts of incomplete or misaligned data.
Validate Category Balance and Sample Size#
Many visualizations assume that groups being compared are roughly comparable in size. When this assumption is violated, plots can unintentionally overemphasize patterns that are driven by uneven sample sizes rather than meaningful differences.
Validating category balance means checking how many observations contribute to each group and ensuring that distributional shapes, averages, or trends are not overinterpreted when based on small samples.
Example 1: Distribution shape vs number of observations
Violin plots and KDE-based visualizations emphasize distribution shape, but they do not communicate how many observations produced that shape. Groups with very different sample sizes can appear visually similar.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.violinplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 hue="location_type",
8 split=True,
9 ax=ax
10)
11
12ax.set_title("Order Total Distributions by Payment Method and Location Type")
13plt.show()
Without additional context, it is easy to assume that each half of a split violin is supported by a similar number of observations.
A simple validation step is to inspect group counts directly:
1orders.groupby(["location_type", "payment_method"], observed=True).size()
location_type payment_method
Campus card 14349
cash 1123
digital 10042
other 676
Non-Campus card 20767
cash 7199
digital 14303
other 1121
dtype: int64
Large imbalances should prompt caution when interpreting fine-grained differences in distribution shape.
Example 2: Averages driven by small groups
Bar plots and point plots often summarize groups using averages. When some categories have very few observations, their averages can be unstable or misleading.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.pointplot(
4 data=orders,
5 x="payment_method",
6 y="total_revenue",
7 errorbar=None,
8 linestyle='none',
9 ax=ax
10)
11
12ax.set_title("Average Order Total by Payment Method")
13plt.show()
Before trusting this comparison, validate how many orders contribute to each average:
1orders.groupby("payment_method", observed=True).size()
payment_method
card 35116
cash 8322
digital 24345
other 1797
dtype: int64
If some payment methods have very small counts, differences in averages may reflect noise rather than systematic behavior.
Practical strategies#
When category imbalance is present:
Pair distribution plots with simple count tables
Avoid overinterpreting subtle differences in small groups
Consider collapsing rare categories when appropriate
Use faceting or annotations to make sample size visible
Practical takeaway#
Before interpreting differences across categories, always ask:
How many observations support each group?
Are visual differences proportional to the available data?
Validating category balance helps prevent false confidence in patterns that are driven by scarcity rather than signal.
Validate Axes, Scales, and Encodings#
Even when the data and aggregation are correct, a visualization can still mislead if axes, scales, or visual encodings distort how differences are perceived. Small choices—such as where an axis starts, whether a scale is linear or logarithmic, or how color is applied—can dramatically change interpretation.
Validating axes and encodings ensures that the visual emphasis matches the analytical intent.
Example 1: Axis limits and exaggerated differences
Bar plots and point plots compare magnitudes. When the y-axis does not include zero, small differences can appear much larger than they are.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.pointplot(
4 data=orders,
5 x="order_method",
6 y="total_revenue",
7 errorbar=None,
8 linestyles='none',
9 ax=ax
10)
11
12ax.set_title("Average Order Total (Default Axis)")
13plt.show()
If the y-axis starts above zero, the visual gap between categories may appear exaggerated.
A simple validation step is to explicitly anchor the axis:
ax.set_ylim(bottom=0)
For many magnitude-based plots, this provides a more honest comparison.
Example 2: Consistent scales across facets
Faceted plots enable side-by-side comparison, but only when axes are consistent. Allowing each panel to use its own scale can hide important differences.
1g = sns.FacetGrid(
2 orders,
3 col="location_type",
4 height=4,
5 aspect=1.2
6)
7
8g.map_dataframe(
9 sns.scatterplot,
10 x="items",
11 y="total_revenue",
12 alpha=0.3
13)
14
15g.set_titles(col_template="{col_name}")
16plt.show()
By default, Seaborn uses shared axes for faceted plots. This behavior should be preserved unless there is a strong reason to compare shapes rather than magnitudes.
Additional encoding checks#
Other common encoding issues to validate include:
Using color for too many categories
Relying on color differences without a legend
Encoding quantitative values with area or angle instead of position
Each encoding choice should have a clear purpose and should not obscure the primary comparison.
Practical takeaway#
Before trusting a visualization, check that:
Axis limits do not exaggerate differences
Scales are appropriate and consistent
Visual encodings support, rather than distract from, the comparison
Validating axes and encodings helps ensure that visual emphasis reflects the data rather than the plotting defaults.
Validate Relationships Before Interpretation#
Plots that show relationships between variables can be especially persuasive. A visible trend, correlation, or clustering pattern often invites interpretation, even when the underlying relationship is weak, noisy, or driven by a small subset of observations. Validating relationships means confirming that apparent patterns are stable, representative, and not artifacts of plotting choices or aggregation.
Example 1: Trend lines vs raw data
Regression lines and smoothers summarize relationships, but they can hide important variability.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.regplot(
4 data=orders,
5 x="items",
6 y="total_revenue",
7 scatter_kws={"alpha": 0.3},
8 ax=ax
9)
10
11ax.set_title("Order Size vs Revenue with Trend Line")
12plt.show()
The upward trend suggests a positive relationship, but the spread of points shows substantial variability. A simple validation step is to inspect the raw scatter without the summary line:
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.scatterplot(
4 data=orders,
5 x="items",
6 y="total_revenue",
7 alpha=0.3,
8 ax=ax
9)
10
11ax.set_title("Order Size vs Revenue (Raw Scatter)")
12plt.show()
Comparing these views helps ensure that the trend line is summarizing a genuine pattern rather than imposing structure on noisy data.
Example 2: Relationships driven by subgroups
Relationships can appear strong overall while behaving differently within subgroups.
1fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
2
3sns.scatterplot(
4 data=orders,
5 x="items",
6 y="total_revenue",
7 hue="location_type",
8 alpha=0.3,
9 ax=ax
10)
11
12ax.set_title("Order Size vs Revenue by Location Type")
13plt.show()
If patterns differ across groups, a single trend line may be misleading. Faceting provides a clearer validation:
1g = sns.FacetGrid(
2 orders,
3 col="location_type",
4 height=4,
5 aspect=1.2
6)
7
8g.map_dataframe(
9 sns.scatterplot,
10 x="items",
11 y="total_revenue",
12 alpha=0.3
13)
14
15g.set_titles(col_template="{col_name}")
16plt.show()
This reveals whether the relationship is consistent or driven by a subset of the data.
Practical takeaway#
Before interpreting relationships:
Inspect raw data alongside summaries
Check whether trends hold within meaningful subgroups
Be cautious about inferring strength or causality from visual patterns alone
Validating relationships helps ensure that plots inform understanding rather than reinforce assumptions.
A Minimal Validation Checklist#
Before trusting or communicating a visualization, it is useful to pause and run through a small set of validation questions. This checklist is not exhaustive, but it captures the most common sources of error and misinterpretation encountered during exploratory analysis.
Data shape and grain
What does one row represent?
Is the data at the correct level for the question being asked?
Aggregation
Is any aggregation happening implicitly?
Does the chosen summary statistic match the analytical intent?
Time structure
Are time periods continuous and complete?
Do missing periods represent zero activity or missing data?
Category balance
How many observations support each group?
Are small or rare categories being overinterpreted?
Axes and encodings
Do axis limits exaggerate or minimize differences?
Are scales consistent across panels?
Are visual encodings appropriate for the comparison?
Relationships
Is the pattern visible in the raw data?
Does the relationship hold across subgroups?
Running through these checks takes little time but can prevent subtle errors from shaping conclusions. Visualization is most effective when it is treated not only as a communication tool, but also as a mechanism for testing assumptions and building confidence in the analysis.
Visualization as a Safety Net#
The purpose of validation and sanity checks is not to catch mistakes, but to support good analytical habits. Even careful analysts work with incomplete information, evolving assumptions, and imperfect data. Validation provides a way to slow down just enough to confirm that a plot reflects what was intended.
These checks are lightweight and repeatable. They do not require new tools or complex procedures—only a willingness to pause and ask a few focused questions. Over time, they become part of the natural rhythm of analysis rather than an extra step.
Seen this way, visualization is not only a means of exploration or communication, but also a safety net. By using familiar plots to validate shape, aggregation, balance, and structure, you reduce the risk of overinterpretation and increase confidence in your conclusions.
These habits carry forward into exploratory data analysis more broadly, where plots evolve quickly and questions shift often. The goal is not perfection, but clarity—and validation is one of the most effective ways to achieve it.
Chapter Summary#
This chapter introduced Seaborn as a high-level visualization library designed to support analytical thinking, not just attractive graphics. Building on the foundations established with Matplotlib, Seaborn emphasizes structure, comparison, and statistical context while reducing the amount of code required for common analytical plots.
Across the chapter, we organized visualizations by the questions they help answer: distributions, relationships, change over time, composition, and comparison. This framing highlights an important principle: the choice of plot should follow the analytical question, not the other way around.
Key ideas reinforced throughout the chapter include:
Seaborn’s strength lies in sensible defaults and a data-centric model
Aggregation and grouping decisions remain analytical responsibilities
Faceting scales comparisons more effectively than color alone
Minimal customization improves clarity without obscuring intent
Seaborn and Matplotlib are complementary, not competing, tools
We also emphasized the importance of validation—checking data shape, aggregation assumptions, time structure, category balance, and encodings—before interpreting or communicating results. These habits help prevent subtle errors and build confidence in exploratory findings.
Seaborn is especially effective during early and middle stages of analysis, where rapid iteration and comparison matter more than fine-grained control. When additional precision is needed, dropping down to Matplotlib remains a natural and expected step.
The next chapter focuses on exploratory data analysis (EDA) as a workflow rather than a collection of plots. There, visualization becomes one part of a broader process of asking questions, forming hypotheses, validating assumptions, and refining understanding over time.