Lesson 29 of 41
Distribution & Trend Visualizations: Line Charts, Histograms & Box Plots
Overview & Learning Objectives
Understanding the underlying distribution of business metrics is fundamental to statistical process control and predictive modeling. While summary statistics (mean, median) condense data into single points, they often conceal skewness, bimodality, and extreme outliers. Visualizing distributions via histograms, Kernel Density Estimation (KDE), and Tukey box plots reveals variance and operational anomalies.
- Plot multi-series time-series line charts with formatted date axes and markers.
- Construct frequency histograms with custom binning and overlaid Kernel Density Estimation (KDE) curves.
- Generate Tukey box plots and violin plots to identify distribution spread, interquartile ranges, and outliers.
Industry Standard
Standard: Risk analytics teams at Goldman Sachs and JPMorgan enforce box plot outlier reviews prior to building credit risk scorecards to detect anomalous fraudulent data entries.
Real-World Example: ScoopCraft Dark-Store Delivery Duration Diagnostics
ScoopCraft analyzes 50,000 delivery completion times across four delivery zones to detect SLA failure risks.
| Zone | Median Delivery (Min) | IQR (Q3 - Q1) | Outlier Threshold (> 1.5 IQR) | SLA Status |
|---|---|---|---|---|
| Zone 1 (Core Urban) | 14.2 min | 4.8 min | > 21.4 min | Optimal (98.2% in SLA) |
| Zone 2 (Suburban) | 22.0 min | 7.5 min | > 33.2 min | Acceptable (94.5% in SLA) |
| Zone 3 (Highway Outer) | 31.5 min | 12.0 min | > 49.5 min | At Risk (82.1% in SLA) |
| Zone 4 (Hill Area) | 38.0 min | 15.5 min | > 61.2 min | Severe Breach (71.0% in SLA) |
Syntax & Core Code Implementation
import matplotlib.pyplot as plt
import seaborn as sns
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5), dpi=150)
# Histogram with KDE overlay
sns.histplot(df['delivery_min'], kde=True, bins=30, color='#6366f1', ax=ax1)
ax1.axvline(df['delivery_min'].median(), color='red', linestyle='--', label='Median')
ax1.set_title('Delivery Time Distribution')
ax1.legend()
# Box plot by zone
sns.boxplot(x='zone', y='delivery_min', data=df, palette='Blues', ax=ax2)
ax2.axhline(30, color='red', linestyle=':', label='30-Min SLA Threshold')
ax2.set_title('Delivery Time by Delivery Zone')
ax2.legend()
plt.tight_layout()
plt.show()
Parameters & Arguments Breakdown
bins: Number of equal-width bins or exact bin edge boundaries.kde: Computes a Gaussian Kernel Density Estimate curve smoothing the histogram.whis: In boxplot, whisker length as multiplier of IQR (default 1.5; points beyond are plotted as outlier fliers).
Step-by-Step Implementation
- Analyze Metric Skewness: Plot a histogram with KDE to inspect whether distribution is Normal, right-skewed, or bimodal.
- Segment by Dimension using Box Plots: Group continuous metric by categorical operational zones using `sns.boxplot(x="zone", y="metric")`.
- Annotate Business Thresholds: Draw vertical/horizontal reference lines (`ax.axvline()`, `ax.axhline()`) highlighting SLA targets or regulatory ceilings.
Common Mistakes & Limitations
- Choosing arbitrary bin sizes for histograms that mask multi-modal distributions or create artificial jagged patterns.
- Relying solely on mean and standard deviation for heavily skewed data (like purchase revenue) instead of median and IQR.
- Omitting legend labels on threshold reference lines, confusing executive stakeholders.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Toggle comments on threshold markers | Ctrl + / | Cmd + / |
Pro Tips & Modern Best Practices
- Overlay a semi-transparent `sns.stripplot(..., jitter=0.2, alpha=0.3)` on top of box plots to display individual data density alongside Tukey quartiles.
- Use Freedman-Diaconis rule (`bins="fd"`) in `np.histogram()` or `sns.histplot()` to compute statistically optimal bin widths automatically.