Data Visualization: Matplotlib & Seaborn Statistical Plots

A chart is only effective if it communicates an immediate, unambiguous insight. In this class, we master Matplotlib (object-oriented canvas control) and Seaborn (high-level statistical charts) to produce publication-grade figures.

The 4 Core Statistical Plot Categories in Seaborn

Category Functions Primary Insight
Distribution sns.histplot, sns.kdeplot, sns.ecdfplot Univariate distribution shape, skewness, probability densities, empirical CDF.
Categorical sns.boxplot, sns.violinplot, sns.stripplot Compare numeric spread across categories; detect multimodality and outliers.
Relational sns.scatterplot, sns.lineplot, sns.regplot Correlation, linear trends, heteroscedasticity, confidence intervals.
Matrix / Grids sns.heatmap, sns.pairplot, sns.clustermap Feature correlation matrices, hierarchical clustering, multi-feature pairwise views.

Hands-On Python: High-Impact Statistical Visualizations

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

# Set clean aesthetic theme
sns.set_theme(style="ticks", palette="pastel")
fig, axes = plt.subplots(1, 2, figsize=(14, 5), dpi=150)

# Generate sample dataset
np.random.seed(42)
df = pd.DataFrame({
    'tenure_months': np.random.gamma(shape=3, scale=8, size=500),
    'monthly_charges': np.random.normal(loc=70, scale=20, size=500),
    'contract_type': np.random.choice(['Month-to-Month', 'One-Year', 'Two-Year'], size=500)
})

# Subplot 1: Violin Plot of Monthly Charges by Contract
sns.violinplot(
    data=df, x='contract_type', y='monthly_charges', 
    ax=axes[0], inner='quartile', palette='Set2'
)
axes[0].set_title("Monthly Charges Density by Contract Tier", fontsize=13, fontweight='bold')
axes[0].set_ylabel("Monthly Spend ($)")

# Subplot 2: Correlation Heatmap
corr = df[['tenure_months', 'monthly_charges']].corr()
sns.heatmap(
    corr, annot=True, cmap="vlag", vmin=-1, vmax=1, 
    ax=axes[1], cbar_kws={'label': 'Pearson Correlation'}
)
axes[1].set_title("Correlation Matrix Heatmap", fontsize=13, fontweight='bold')

sns.despine(trim=True)
plt.tight_layout()
plt.savefig("statistical_summary.png", dpi=300)
plt.show()

University Viva & Exam Checklist

What is the Object-Oriented (OO) vs. State-Based (pyplot) interface in Matplotlib? (Answer: The pyplot interface operates implicitly on a current global figure; the OO interface explicitly creates Figure and Axes objects: fig, ax = plt.subplots(), providing complete multi-panel canvas control without side-effect bugs).

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the relationship between Matplotlib and Seaborn?

Matplotlib is the foundational, low-level plotting engine that gives pixel-perfect control over every canvas element. Seaborn is a high-level statistical visualization library built directly on top of Matplotlib that integrates seamlessly with Pandas DataFrames to generate beautiful statistical figures with concise code.

Q2. When should I use a Violin Plot over a Box Plot?

A Box Plot displays quartiles and outlier fences, but conceals multimodal distributions (e.g., bimodal data with two distinct peaks looks identical to uniform data in a box plot). A Violin Plot combines a box plot with a rotated kernel density estimate (KDE), revealing the true density shape of the distribution.

Q3. How do you plot a correlation heatmap in Seaborn?

Compute the correlation matrix using df.corr(), and pass it to sns.heatmap(corr, annot=True, cmap='RdBu', vmin=-1, vmax=1, fmt='.2f').

Q4. What is a Seaborn FacetGrid / PairGrid?

FacetGrids map a dataset onto multiple subplots arranged in a grid based on categorical levels (e.g., rendering one scatter plot per country or product tier), enabling effortless multi-dimensional visual slicing.

Q5. How do I make Matplotlib charts look modern and professional?

Apply Seaborn themes (sns.set_theme(style='whitegrid')), remove unnecessary top and right axis spines (sns.despine()), use clean colorblind-friendly palettes, and set DPI to 300 for crisp rendering.

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

Exploratory Data Analysis Framework

Apply statistical visualizations to systematically audit tabular datasets.

Interactive Visualization with Plotly

Elevate static Seaborn plots into interactive web graphics.

Time Series Analysis & Trends

Plot line graphs with rolling averages and seasonal decomposition.

Streamlit Business Intelligence Dashboards

Embed Matplotlib and Seaborn figures into interactive web applications.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!