Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 64/ 160
04. Data Visualization & BI

Histograms, KDE & Box/Violin Plots

Visualize distributions with histograms, density estimates, and box/violin summaries.

BeginnerHistogram · KDE3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

These charts show how your numbers are spread out: where most of them sit, how far they stretch and whether there is more than one cluster.

Think of it like…

Looking at a crowd from different heights: a histogram counts people per bay, a KDE smooths the skyline, a box plot gives the five landmarks, and a violin shows the skyline outline with the landmarks inside.

Where you’ve seen it

Delivery times for 1,000 orders have Q1 = 40 min, median 50 and Q3 = 60, so IQR = 20 and the box-plot fences are at 40 − 1.5 × 20 = 10 and 60 + 1.5 × 20 = 90 minutes. The box plot looks healthy, but a violin plot reveals two humps near 40 and 60 minutes: the median of 50 falls in the valley where relatively few orders actually land, because pickup orders (fast) and courier orders (slow) are mixed. For the histogram, the Freedman-Diaconis rule gives bin width 2 × IQR × n^(−1/3) = 2 × 20 / 10 = 4 minutes (25 bins across a 100-minute range), and Silverman's rule gives a KDE bandwidth of about 0.9 × 14.9 × 0.251 = 3.4 minutes. Splitting by order type produces two clean, roughly normal distributions.

Words you’ll hear

Histogram bins
Intervals used to count observations; the width trades detail against noise.
KDE bandwidth
The smoothing width of the kernel; too small is noisy, too large erases structure.
IQR and fences
Q3 − Q1, and the 1.5 × IQR limits beyond which points are drawn as outliers.
Multimodality
More than one peak, often a sign of mixed subpopulations.

Visual diagram

Loading interactive diagram

Theory & deep dive

Histograms and KDEs

A histogram's appearance depends on bin width. Too many bins give a spiky picture of noise; too few hide structure. Rules of thumb: Sturges (k = 1 + log₂ n; about 11 bins for n = 1,000) works for roughly normal data; Scott (width = 3.49 σ n^(−1/3)) and Freedman-Diaconis (width = 2 × IQR × n^(−1/3)) adapt to spread, and Freedman-Diaconis is more robust to outliers. In Matplotlib and Seaborn use bins="fd", "auto" or an explicit binwidth. Use density (stat="density") rather than counts when comparing groups of different sizes, and fix the bin edges when overlaying histograms.

A KDE replaces bars with a smooth curve: each point contributes a kernel (usually Gaussian) of width h, the bandwidth. Silverman's rule gives h = 0.9 × min(σ, IQR/1.34) × n^(−1/5); in Seaborn bw_adjust scales it (kdeplot(..., bw_adjust=0.5) for more detail). KDEs can leak beyond natural limits (negative durations) unless you use cut=0 or clip, and they smooth away sharp features such as spikes at zero or at round numbers. An ECDF plot (sns.ecdfplot) avoids binning entirely and is excellent for comparing groups and reading percentiles.

Computing a bin width

n = 1,000, IQR = 20, range = 100. Freedman-Diaconis: width = 2 × 20 × 1000^(−1/3) = 40 / 10 = 4, so about 100 / 4 = 25 bins. Sturges would use 1 + log₂ 1000 ≈ 11 bins and smooth over the two humps.

Key takeaway: Choose bins and bandwidth with a rule, then vary them; use density for unequal groups and ECDFs for precision.

Box and violin plots, and combining views

A box plot draws the box from Q1 to Q3 (the IQR), a line at the median, whiskers to the most extreme points within 1.5 × IQR of the box, and individual points beyond as outliers. It is compact and great for comparing many groups, but it shows only five summary numbers, so a bimodal distribution and a flat one can look identical. A violin plot adds a KDE outline for each group (with inner="quartile" or inner="box"), revealing shape, skew and multiple modes; it needs enough data per group (dozens at least) and inherits KDE caveats. Boxen (letter-value) plots extend box plots with more quantile boxes for large samples.

Practical use: start with a histogram or ECDF of the whole variable, check for skew (a long right tail suggests a log scale or transform), then compare groups with box or violin plots, adding raw points (stripplot) for small samples. Mark the mean and median separately when they differ. Be careful with outlier flags: 1.5 × IQR is a visual convention, not a rule for deleting data. For skewed positive data a log axis (ax.set_xscale("log")) often turns a long tail into a readable shape. Always label units and the sample size per group.

Box plot fences

Q1 = 40, Q3 = 60, IQR = 20. Lower fence = 40 − 30 = 10 and upper fence = 60 + 30 = 90. A delivery of 105 minutes is drawn as an outlier point, but it is real data worth investigating, not automatically an error.

Key takeaway: Use boxes for compact group comparison and violins or histograms when shape (modes, skew) matters.

How it works, step by step

Step 1 of 4
Analyst

1. Plot the raw distribution

Draw a histogram with a reasoned bin rule and an ECDF; note skew, spikes and outliers.

bins="fd" → 25 bins
Key numbers at this step
Try
several widths

When to use it & trade-offs

What it is

Distribution plots show the full shape of a variable instead of a single summary. A histogram counts observations in bins; a KDE (kernel density estimate) draws a smooth curve by placing a small bump at every observation and summing them; a box plot compresses the distribution into the median, the quartiles (IQR) and whiskers with outlier points; a violin plot mirrors a KDE around a box summary. Each hides or reveals different things: bin width controls what a histogram shows, bandwidth controls a KDE, and a box plot cannot show multimodality at all.

Why it matters: Means and standard deviations describe a distribution only if it is roughly symmetric and unimodal. Real data (latency, income, session length, error residuals) is skewed, heavy-tailed or bimodal, and decisions about transformations, outlier handling, model choice and segmentation depend on seeing that shape. Understanding how bin and bandwidth choices change the picture protects you from over-reading noise or hiding structure.

When to reach for it

  • Checking skew and outliers before modelling
  • Comparing a metric across segments or experiment arms
  • Choosing transformations such as logs

When to avoid or be careful

  • Trusting a box plot to rule out multiple modes
  • Reporting mean and SD for obviously skewed data
  • Leaving the default bins without checking alternatives

Distribution plot options

Histogram
Best for: Seeing counts and shape for one variable

Strengths: Intuitive; exact counts.

Watch out: Sensitive to bin width and edges.

KDE or violin
Best for: Smooth shape, modes and group comparison

Strengths: No bin artefacts; reveals multimodality.

Watch out: Bandwidth sensitive; may extend past valid range.

Box plot
Best for: Comparing many groups' median and spread

Strengths: Compact; robust summaries.

Watch out: Hides multimodality and sample size.

Interview signals & numbers to know

When this topic comes up

  • “The median is in a gap”
  • “What does the distribution of X look like?”
  • “Compare distributions by segment”
  • Freedman-Diaconis bins
  • Violin versus box plot

Benchmarks & rules of thumb

1.5 × IQR -
box-plot whisker and outlier convention
n^(−1/3) -
scaling of Scott and Freedman-Diaconis bin widths
0.9 × min(σ, IQR/1.34) × n^(−1/5) -
Silverman's KDE bandwidth rule

Common mistakes & follow-ups

Common interview mistakes

  • Comparing histograms of unequal groups using counts instead of density.
  • Deleting every point beyond the 1.5 × IQR fence.
  • Reading a violin plot built from five observations as a real shape.

Likely interviewer follow-ups

  • How do you choose the number of bins?
  • When is a box plot misleading?
  • How would you compare distributions across 8 segments?
Interview tip: Mention that a box plot can't show bimodality and that you'd check a histogram or violin first. It shows you read distributions before summarising them.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Histograms, KDE & Box/Violin Plots with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Statistical Plotting with Seaborn
Next topic
Scatter Plots, Pair Plots & Heatmaps