Data Visualization
Data visualization is the graphical representation of data and information. The human visual system detects patterns, trends and outliers in a picture far faster than in a table of numbers — which is why visualization is both an analysis tool (EDA) and a communication tool (reporting).
Why Visualize?
| Purpose | Example |
|---|---|
| Spot patterns and trends | A sales line chart reveals seasonality instantly |
| Identify outliers | One dot far from the cloud in a scatter plot |
| Compare categories | Bar chart of revenue by region |
| Show distribution | Histogram exposes skew a mean would hide |
| Show relationships | Scatter plot of advertising vs sales |
| Communicate to non-technical audiences | A dashboard the management can read in 30 seconds |
| Reveal what statistics hide | Anscombe's quartet — identical stats, different shapes |
Choosing the Right Chart
Chart Reference Table
| Chart | Best for | Data types | Avoid when |
|---|---|---|---|
| Bar chart | Comparing categories | 1 categorical + 1 numeric | Too many categories (>15) |
| Column chart | Comparison over few time periods | Same | Long category names |
| Line chart | Trends over continuous time | Time + numeric | Unordered categories |
| Pie chart | Parts of a whole | 1 categorical proportion | More than 5–6 slices; comparing across pies |
| Histogram | Distribution of one numeric variable | 1 numeric (continuous) | Categorical data |
| Box plot | Distribution summary + outliers, group comparison | Numeric, optionally by group | Showing exact shape/multi-modality |
| Scatter plot | Relationship between two numerics | 2 numeric | Heavy overplotting (use alpha/hexbin) |
| Heatmap | Matrix of values, correlations | Matrix | Few data points |
| Bubble chart | 3 variables (x, y, size) | 3 numeric | Precise size comparison |
| Area chart | Cumulative totals over time | Time + numeric | Many overlapping series |
| Violin plot | Distribution shape by group | Numeric by category | Small samples |
Principles of Effective Visualization
1. Edward Tufte's Data-Ink Ratio
Ink used to display data
Data-Ink Ratio = ─────────────────────────── -> maximise this
Total ink used in the graphic
Remove chartjunk: 3-D effects, heavy gridlines, decorative backgrounds, unnecessary borders, gradient fills, drop shadows.
2. Core Rules
| Principle | Rule |
|---|---|
| Start the y-axis at zero | For bar charts — truncating exaggerates differences |
| Use a clear title | State the insight, not just the variable names |
| Label axes with units | "Revenue (₹ lakh)" not "Revenue" |
| Order meaningfully | Sort bars by value, not alphabetically (unless order matters) |
| Limit colours | 5–7 max; use colour to encode meaning, not decoration |
| Be consistent | Same colour = same category across every chart in a report |
| Avoid dual y-axes | They can imply relationships that don't exist |
| Direct-label where possible | Better than forcing the eye to a legend |
| Design for accessibility | ~8% of men have colour-vision deficiency — never rely on red/green alone |
3. Common Misleading Practices
Visual Encoding — Ranked by Human Accuracy
Cleveland and McGill's classic ranking of how accurately people decode visual channels:
1. Position along a common scale <- most accurate (bar, scatter)
2. Position on identical, non-aligned scales
3. Length
4. Angle / Slope (pie charts live here — hence their weakness)
5. Area (bubble charts)
6. Volume / Depth
7. Colour saturation / Shading <- least accurate
Design implication: whenever precision matters, encode with position or length, not with area or colour.
Python Visualization Ecosystem
| Library | Type | Best for |
|---|---|---|
| Matplotlib | Static, low-level | Full control, publication figures |
| Seaborn | Static, statistical | Beautiful defaults, statistical plots (built on Matplotlib) |
| Pandas .plot() | Static, quick | Fast exploration straight from a DataFrame |
| Plotly | Interactive | Dashboards, hover/zoom, web embedding |
| Bokeh | Interactive | Streaming and large-data web apps |
| Altair | Declarative | Grammar-of-graphics style specifications |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid") # clean default styling
sales = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
"revenue": [420, 465, 448, 512, 590, 634],
"region": ["North", "North", "South", "South", "East", "East"],
})
fig, axes = plt.subplots(2, 2, figsize=(13, 9))
# 1. LINE — trend over time
axes[0, 0].plot(sales["month"], sales["revenue"], marker="o", color="#168B99", linewidth=2)
axes[0, 0].set_title("Revenue Grew 51% from Jan to Jun", fontsize=12, fontweight="bold")
axes[0, 0].set_ylabel("Revenue (Rs lakh)")
# 2. BAR — comparison, sorted, starting at zero
axes[0, 1].bar(sales["month"], sales["revenue"], color="#10b981")
axes[0, 1].set_ylim(0, 700) # zero baseline — honest comparison
axes[0, 1].set_title("Monthly Revenue")
# 3. PIE — composition (few slices only)
region_totals = sales.groupby("region")["revenue"].sum()
axes[1, 0].pie(region_totals, labels=region_totals.index, autopct="%1.1f%%",
colors=["#168B99", "#10b981", "#f59e0b"])
axes[1, 0].set_title("Revenue Share by Region")
# 4. HORIZONTAL BAR — long labels read better horizontally
axes[1, 1].barh(sales["month"], sales["revenue"], color="#6366f1")
axes[1, 1].set_title("Revenue by Month")
axes[1, 1].set_xlabel("Revenue (Rs lakh)")
plt.tight_layout()
plt.show()
# Removing chartjunk — before/after
fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(sales["month"], sales["revenue"], color="#168B99")
# Maximise data-ink: strip the top/right spines and heavy gridlines
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.grid(axis="y", alpha=0.3)
ax.set_axisbelow(True)
ax.set_title("Revenue climbed every month except March", loc="left",
fontsize=13, fontweight="bold")
ax.set_ylabel("Rs lakh")
# Direct labels beat a legend
for i, v in enumerate(sales["revenue"]):
ax.text(i, v + 8, str(v), ha="center", fontsize=9)
plt.tight_layout()
plt.show()
Dashboards
A dashboard presents multiple related visualizations on one screen for monitoring key metrics.
| Dashboard type | Purpose | Audience |
|---|---|---|
| Operational | Real-time monitoring of live processes | Operations team |
| Analytical | Deep exploration of historical trends | Analysts |
| Strategic | High-level KPIs against targets | Executives |
Design rules: most important metric top-left (F-pattern reading), 5–9 visuals maximum, consistent colour meanings, filters/slicers for interactivity, and every chart must answer a question someone actually asks.
The next three lessons take the three most examined chart types — histogram, box plot, scatter plot — and go deep on how to build and read each one.