Data Preparation / Data Preprocessing Slides 📂 Introduction · 3 of 13 38 min read

Data Visualization & Pattern Detection: A Practical Guide

Data visualization turns raw numbers into patterns you can actually see and act on. This guide covers why visuals matter (Anscombe's quartet proves stats alone can mislead), how to pick the right chart, and how to spot trends, seasonality, clusters, correlations, and outliers. Includes distribution, relationship, and time-series techniques plus anomaly detection with rolling means and z-scores.

📊

Data Visualization & Pattern Detection

A chart isn't decoration — it's a form of analysis. The right plot exposes trends, clusters, correlations, and anomalies that a table of statistics quietly hides.
Trends Seasonality Clusters Anomalies

Press Next → or use ← → arrow keys

Section 01

Visualization IS Analysis

Treat every chart as a hypothesis test
You expect sales to climb toward the holidays. You plot the line — and either the picture confirms it, or it shows a surprise dip you'd never have caught in a spreadsheet. Each chart quietly asks: "does reality match what I expected?"

That's why data visualization is not decoration — it's analysis. Summary numbers compress away exactly the trends, groupings, and outliers you most need to see. A good plot puts them back on screen where your eyes can catch them in seconds.
📉
Statistics Without Pictures Is Dangerously Incomplete

Four datasets can share the same mean, variance, and correlation yet look nothing alike — a fact known as Anscombe's Quartet. Rely on the numbers alone and you'll miss curves, outliers, and clusters entirely. The next slide shows exactly how.

Section 01 · Proof

Anscombe's Quartet — Always Plot First

① clean linear r = 0.82 ② curved r = 0.82 ③ line + outlier r = 0.82 ④ vertical + point r = 0.82
👁️
Identical Statistics, Four Different Stories

All four share the same mean (~9), variance (~11), and correlation (~0.82) — yet a line, a curve, an outlier-wrecked line, and a near-vertical stack couldn't be more different. The summary numbers are blind to this; a five-second scatter plot reveals it instantly. Rule one of visualization: plot before you compute.

Section 02 · Choose

Match The Chart To The Question

One variable's distribution? Histogram · KDE · Violin Two numeric variables? Scatter · Joint plot Change over time? Line · Area chart Compare categories? Bar · Grouped bar Many variables at once? Heatmap · Pair plot Spot outliers? Box plot · Strip plot
🥧
And Please, Avoid The Pie Chart

The eye judges lengths far better than angles, so pie charts make it nearly impossible to compare similar slices accurately. Almost any pie chart is clearer as a bar chart. Start from the question, and the right chart usually picks itself.

Section 03 · Distributions

Seeing One Variable's Shape

import seaborn as sns

# histogram + smooth KDE curve
sns.histplot(df['purchase_amount'], bins=40, kde=True)

# split the distribution by a category
sns.histplot(df, x='purchase_amount', hue='gender', kde=True, alpha=0.6)
📊
Shape Tells You What You're Dealing With

A right-skew (a long tail of big spenders) says the mean will mislead — report the median. A bimodal shape (two humps) is a giveaway that two sub-populations are mixed together, which the hue= split can confirm. Histograms, KDEs, and violins all answer the same question: what does this one column actually look like?

Section 03 · Relationships

Comparisons, Relationships & Outliers

# category comparison + outliers in one plot
sns.boxplot(data=df, x='product_category', y='purchase_amount')

# two numerics, colour-encoded by a third variable
sns.scatterplot(data=df, x='age', y='purchase_amount', hue='income_bracket')

# everything at once — correlation heatmap (upper triangle masked)
corr = df.select_dtypes('number').corr().round(2)
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0, vmin=-1, vmax=1)
🌡️
The Heatmap Does Triple Duty

A correlation heatmap shows, in one glance, which features drive your target (say income → purchase at +0.78), which work against it (delivery days → rating at −0.44), and which mirror each other. Any pair above |r| > 0.85 is a multicollinearity flag — candidates to drop.

Section 04 · Patterns

Five Patterns To Hunt For

Trend steady rise/fall Seasonality repeating cycles Clusters natural groups Correlation move together Outlier the odd one out
🔎
Know What You're Looking For

Trends (steady direction), seasonality (repeating cycles), clusters (natural groups), correlations (variables moving together), and outliers (points that don't belong). Naming the pattern you're hunting tells you which chart to reach for.

Section 04 · Time

Trends & Seasonality Over Time

# daily totals, then a 7-day rolling average to reveal the trend
df['order_date'] = pd.to_datetime(df['order_date'])
daily = df.groupby('order_date')['purchase_amount'].sum().reset_index()
daily['rolling_7d'] = daily['purchase_amount'].rolling(7).mean()
🌊
Smooth The Noise, See The Signal

Raw daily data is jagged. A rolling average (here 7-day) irons out the day-to-day jitter so the underlying trend stands out. Meanwhile a monthly bar chart exposes seasonality — the November–December peaks that repeat every year. Line charts for trends, bars for cyclical patterns.

📅
Parse Dates First

pd.to_datetime() is the essential first move — until a column is a real datetime, you can't resample, roll, or group by month. Time-series patterns only appear once the time axis is genuinely a time axis.

Section 05 · Anomalies

Catching Anomalies With A Control Band

time → spike > +2σ 🚨 daily revenue 7-day rolling mean ± 2σ band
📈
Draw The Normal Range, Flag What Escapes It

Compute a rolling mean and rolling standard deviation, then draw a band at mean ± 2σ. Any day whose revenue jumps outside that band is an anomaly — a marketing spike, a system glitch, or a data error worth investigating. The band adapts as the trend moves, so it stays meaningful over time.

Section 05 · Methods

Two Ways To Flag The Unusual

〰️
Rolling ± 2σ Band
For time series: flag points outside a moving mean ± 2 standard deviations. Adapts to trends and seasonality.
📏
Z-Score |z| > 3
For roughly-normal columns: flag values more than 3σ from the mean. Simple, global, no time axis needed.
📦
IQR Fences
For skewed data: box-plot fences at Q1/Q3 ± 1.5×IQR. Robust, distribution-free — the safe default.
🔍
A Flag Is A Question, Not A Verdict

Before you touch a flagged point, ask: is it a data-quality error (a typo, a sensor fault) or a genuine event (a real sales spike, a fraud attempt)? Never delete anomalies silently — investigate first and document every removal. The interesting outlier is often the whole point of the analysis.

Section 06 · Tools

matplotlib · seaborn · plotly

📐
matplotlib
the foundation
Total control, publication-quality figures. Verbose, but everything else is built on top of it.
🎨
seaborn
EDA workhorse
Beautiful statistical charts in one line — histplot, boxplot, heatmap, pairplot. Your day-to-day EDA tool.
🖱️
plotly
interactive
Hover, zoom, and pan. Ideal for dashboards and sharing findings with stakeholders who want to explore.
🧰
Pick By Context

Reach for seaborn while exploring, plotly when the audience needs to interact, and matplotlib when you need pixel-perfect control for a report or paper. They interoperate — seaborn returns matplotlib axes you can fine-tune.

Section 07 · Craft

What Makes A Chart Honest & Clear

❌ Avoid✅ Do
Truncated axis (bar not starting at 0)Start bar-chart axes at zero
Colour as decorationColour to encode information
Chartjunk: gridlines, 3-D, gradientsStrip everything non-essential
Pie charts for comparisonBar charts — the eye reads length
Leaving the reader to guessAnnotate the insight directly on the chart
⏱️
The Five-Second Test

A good chart delivers its main message in about five seconds. If a viewer has to squint, decode a legend, or hunt for the point, simplify: fewer elements, a clearer title, a direct annotation. And never distort — a truncated axis can turn a 2% change into a visual cliff.

Section 08 · Golden Rules

Seven Rules For Visualization

🏅 Data Visualization, Distilled
1Plot before you compute. Anscombe's Quartet proves statistics alone can deceive.
2Match the chart to the question — distribution, comparison, time, relationship, or outliers.
3Start bar axes at zero — a truncated axis is the classic way to mislead.
4Use colour to encode, not decorate. Every hue should carry meaning.
5Investigate anomalies before removing them — and document every decision.
6Pick the tool for the job — seaborn to explore, plotly to share, matplotlib to polish.
7Pass the five-second test. If the message isn't instant, simplify.
Wrap-Up

You Can Now See What The Data Hides

plot!Before stats
Q→chartMatch to question
5Pattern types
±2σAnomaly band
no 🥧Bars beat pies
5-secClarity test
🎯
The Through-Line

Visualization is analysis: each chart tests whether reality matches your expectation. Plot before you compute, match the chart to the question, and learn to spot the five patterns — trend, seasonality, clusters, correlation, and outliers. Then keep it honest: zero-based axes, meaningful colour, and a message readable in five seconds.

📚
Where To Go Next

The patterns and problems you spot here feed straight into data cleaning (fixing the outliers and gaps you found) and feature engineering — turning the trends, seasonality, and relationships you've now seen into features a model can learn from.

📊 End of tutorial · Press to review, or click Restart