Python for Data Analytics & AutomationLesson 29 of 41
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.

ZoneMedian Delivery (Min)IQR (Q3 - Q1)Outlier Threshold (> 1.5 IQR)SLA Status
Zone 1 (Core Urban)14.2 min4.8 min> 21.4 minOptimal (98.2% in SLA)
Zone 2 (Suburban)22.0 min7.5 min> 33.2 minAcceptable (94.5% in SLA)
Zone 3 (Highway Outer)31.5 min12.0 min> 49.5 minAt Risk (82.1% in SLA)
Zone 4 (Hill Area)38.0 min15.5 min> 61.2 minSevere 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

  1. Analyze Metric Skewness: Plot a histogram with KDE to inspect whether distribution is Normal, right-skewed, or bimodal.
  2. Segment by Dimension using Box Plots: Group continuous metric by categorical operational zones using `sns.boxplot(x="zone", y="metric")`.
  3. 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)

ActionWindowsMac
Toggle comments on threshold markersCtrl + /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.