Lesson 30 of 41
Statistical Plotting with Seaborn: barplot, countplot & scatterplot
Overview & Learning Objectives
Seaborn is built directly on top of Matplotlib and deeply integrates with Pandas DataFrames. It simplifies complex statistical visualizations by automating statistical aggregations (like bootstrap confidence intervals on bar charts), providing integrated semantic encodings (`hue`, `size`, `style`), and offering modern color palettes designed for accessibility and clarity.
- Build statistical bar plots with automated error bars (95% bootstrap confidence intervals) using `sns.barplot()`.
- Compute discrete categorical frequencies effortlessly using `sns.countplot()`.
- Construct multi-dimensional relational scatter plots encoding up to 4 variables via `x`, `y`, `hue`, and `size`.
Industry Standard
Standard: Product analytics teams at Airbnb and Uber use Seaborn statistical plots during A/B testing debriefs to display treatment vs control means alongside 95% confidence intervals.
Real-World Example: ScoopCraft Loyalty Tier & Basket Size Analysis
ScoopCraft marketing analyzes customer spend by membership tier and ordering channel (App vs Web vs Store Kiosk).
| Loyalty Tier | Channel | Mean Basket Spend | 95% CI Range | Sample Size (N) |
|---|---|---|---|---|
| Platinum | Mobile App | $54.20 | [$51.80, $56.60] | 12,400 orders |
| Platinum | Store Kiosk | $42.10 | [$39.50, $44.70] | 3,200 orders |
| Standard | Mobile App | $26.80 | [$25.90, $27.70] | 45,000 orders |
| Standard | Store Kiosk | $21.50 | [$20.40, $22.60] | 18,500 orders |
Syntax & Core Code Implementation
import seaborn as sns
import matplotlib.pyplot as plt
# Set aesthetic theme
sns.set_theme(style='whitegrid', font_scale=1.1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6), dpi=150)
# Statistical bar plot with hue and bootstrap confidence interval
sns.barplot(
data=df,
x='loyalty_tier',
y='basket_spend',
hue='channel',
errorbar=('ci', 95),
palette='muted',
ax=ax1
)
ax1.set_title('Mean Basket Spend by Loyalty Tier & Channel')
# Relational scatter plot with 4 dimensional encodings
sns.scatterplot(
data=df,
x='delivery_min',
y='basket_spend',
hue='loyalty_tier',
size='item_count',
sizes=(20, 200),
alpha=0.7,
palette='deep',
ax=ax2
)
ax2.set_title('Spend vs Delivery Time (Size=Items)')
plt.tight_layout()
plt.show()
Parameters & Arguments Breakdown
data: Tidy (long-form) DataFrame where columns map to variables.x, y: Names of variables in data to map to Cartesian coordinates.hue: Grouping variable that produces points or bars with different colors.errorbar: Specifies error representation (e.g. ("ci", 95) for bootstrap interval, "sd" for standard deviation, "se" for standard error).
Step-by-Step Implementation
- Configure Seaborn Theme: Invoke `sns.set_theme(style="whitegrid")` to establish professional typography and gridlines.
- Map Semantic Encodings: Assign categorical split to `hue` and continuous magnitude to `size`.
- Adjust Legend Placement: Relocate overlapping legends outside plot area using `sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))`.
Common Mistakes & Limitations
- Assuming `sns.barplot()` displays total sums; by default it computes the arithmetic mean of each category.
- Using high-saturation default palettes that distort visual perception or fail colorblind accessibility tests; use `palette="colorblind"` or `"crest"`.
- Passing wide-format matrices to relational Seaborn functions instead of molten tidy data.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Run active script in terminal | Ctrl + F5 | Cmd + F5 |
Pro Tips & Modern Best Practices
- In Seaborn >= 0.12, use the new `errorbar=("pi", 90)` parameter for percentile intervals or `errorbar="sd"` for standard deviation instead of deprecated `ci=...`.
- Use `sns.countplot(..., order=df["category"].value_counts().index)` to automatically display category bars in sorted descending frequency order.