Module 5: Data Visualization
Module 5: Data Visualization
Introduction to Data Science โ Week 5
Turning data into clear, honest, and compelling visual stories
Module Overview
Data visualization is the art and science of presenting data in visual form so that patterns,
trends, and relationships can be understood quickly. This module covers the principles of
effective visualization, the major chart types and when to use them, how to build charts with
matplotlib and seaborn, and how to avoid misleading visualizations. Students will practice
designing charts that communicate clearly and honestly.
Learning Objectives
By the end of this module, students will be able to:
- Explain why visualization is essential for understanding data.
- Choose the right chart type for different kinds of data and questions.
- Build bar charts, line charts, scatter plots, histograms, and box plots in Python.
- Apply principles of good design: clarity, honesty, and simplicity.
- Recognize and avoid misleading visualizations.
- Create a small multi-chart visual narrative from a dataset.
Lesson 1: Why Visualize Data?
Humans are highly visual creatures. Our brains can spot patterns in a chart far faster than
in a table of numbers. A well-designed chart can make a pattern obvious that would otherwise
be buried in hundreds of rows.
๐จ Think of it like this: A chart is a picture of your data. Just like a
picture is worth a thousand words, a good chart is worth a thousand numbers.
What Visualization Does
- Reveals patterns, trends, and outliers at a glance.
- Supports EDA by helping you "see" the shape of your data.
- Communicates findings to stakeholders who don't read code or statistics.
- Surfaces data quality issues (e.g., gaps, extreme values, clusters).
๐ก Key Idea: Visualization is not just a final presentation step โ it's a
critical tool during analysis. Most EDA is done visually.
Lesson 2: Choosing the Right Chart
The right chart depends on the question you're asking and the type of data you have.
| Goal |
Best Chart |
Example |
| Compare categories |
Bar chart |
Sales by region |
| Show change over time |
Line chart |
Monthly revenue over a year |
| Show the distribution of one variable |
Histogram or box plot |
Distribution of customer ages |
| Show the relationship between two variables |
Scatter plot |
Advertising spend vs. sales |
| Show parts of a whole |
Pie or donut chart (use sparingly) |
Market share by product |
| Show distribution across categories |
Box plot or violin plot |
Test scores by class |
| Show correlation between many variables |
Heatmap (correlation matrix) |
Correlations among all numeric columns |
โ ๏ธ Pie Chart Warning: Pie charts are only useful for showing parts of a whole
with a small number of slices (5 or fewer). For anything else, a bar chart is almost always
more readable.
๐ Think of it like choosing a tool: You wouldn't use a hammer to cut bread.
Each chart is a tool โ use the right one for the job.
Lesson 3: Building Charts with matplotlib
matplotlib is the foundational Python library for plotting.
seaborn builds on it and provides nicer default styling and
statistical plots.
Setup
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# Load cleaned data
data = pd.read_csv("clean_data.csv")
Bar Chart
avg_sales = data.groupby("region")["sales"].mean()
plt.figure(figsize=(8, 5))
avg_sales.plot(kind="bar", color="steelblue")
plt.title("Average Sales by Region")
plt.xlabel("Region")
plt.ylabel("Average Sales ($)")
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
Line Chart
monthly = data.groupby("month")["revenue"].sum()
plt.figure(figsize=(8, 5))
plt.plot(monthly.index, monthly.values, marker="o", color="teal")
plt.title("Monthly Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue ($)")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
Scatter Plot
plt.figure(figsize=(8, 5))
plt.scatter(data["ad_spend"], data["sales"], alpha=0.6, color="coral")
plt.title("Advertising Spend vs. Sales")
plt.xlabel("Ad Spend ($)")
plt.ylabel("Sales ($)")
plt.tight_layout()
plt.show()
Histogram
plt.figure(figsize=(8, 5))
plt.hist(data["age"], bins=20, color="mediumseagreen", edgecolor="black")
plt.title("Distribution of Customer Ages")
plt.xlabel("Age")
plt.ylabel("Frequency")
plt.tight_layout()
plt.show()
Box Plot
plt.figure(figsize=(8, 5))
sns.boxplot(x="class", y="score", data=data, palette="Set2")
plt.title("Test Scores by Class")
plt.xlabel("Class")
plt.ylabel("Score")
plt.tight_layout()
plt.show()
๐ก Key Idea: Every chart should have a title,
labeled axes, and (where relevant) a legend. A chart without
labels is like a book without a cover โ nobody knows what it's about.
Lesson 4: Principles of Good Design
Good data visualization follows a few simple principles:
1. Clarity Over Decoration
- Remove unnecessary gridlines, borders, and colors.
- Don't use 3D effects โ they distort perception.
- Choose a single clear message per chart.
2. Honesty
- Always start bar charts at zero.
- Use consistent scales across charts you're comparing.
- Don't cherry-pick time ranges to support a narrative.
- Label units clearly.
3. Accessibility
- Use colorblind-friendly palettes (e.g., seaborn's "colorblind" palette).
- Ensure sufficient contrast between colors.
- Don't rely on color alone to convey meaning โ use shape or labels too.
4. Context
- Add titles that state the finding, not just the variable name.
- Include reference lines (e.g., a target or average).
- Provide units and data sources.
๐ก Key Idea: The goal of a chart is understanding, not decoration.
If removing an element makes the chart easier to read, remove it.
Lesson 5: Misleading Visualizations
Not all charts are honest. Some deliberately or accidentally mislead the viewer:
Common Tricks
| Trick |
What It Does |
Why It's Misleading |
| Cut-off y-axis |
Starts at a high value instead of 0 |
Makes small differences look huge |
| 3D charts |
Adds visual depth |
Distorts the perceived size of bars or slices |
| Truncated time range |
Shows only a convenient window of time |
Hides trends outside the window |
| Wrong chart type |
E.g., pie chart with 15 slices |
Makes comparison impossible |
| Inconsistent scales |
Different axes on side-by-side charts |
Makes comparisons invalid |
Cut-Off Y-Axis in Action
โ Misleading: โ
Honest:
โ โ โ โ
โ โ โ โ โ โ
โ โ โ โ โ โ
โโโโโดโโโโโดโโโ โโโโโดโโโโโดโโโ
A B 0 A B
(starts at 90) (starts at 0)
โ ๏ธ Be a Chart Detective: When you see a chart, ask:
- Where does the y-axis start?
- Is the chart type appropriate?
- Are labels and units clear?
- Who made this chart, and why?
Lesson 6: Multi-Chart Narratives
In real analyses, you rarely present a single chart. Instead, you build a
visual narrative โ a sequence of 2โ4 charts that together tell a
story.
Principles for Visual Narratives
- Start with context: Show the big picture first (e.g., overall trend).
- Zoom in: Use subsequent charts to explore specific details or subgroups.
- End with a takeaway: Your final chart should make the conclusion obvious.
- Consistent style: Use the same colors, fonts, and layout across charts.
- One message per chart: Don't try to cram multiple insights into one chart.
๐ฌ Think of it like a movie: Each chart is a scene. A good data story has a
beginning (context), a middle (exploration), and an end (conclusion). Jumping straight to the
conclusion without context loses the audience.
๐ก Key Idea: Use 2โ4 charts maximum in any presentation. Too many charts
overwhelm the audience. Pick the ones that tell the clearest story.
Hands-On Lab: Build a Visual Narrative
Goal: Create a set of 3โ4 charts that together tell a story about a dataset.
Instructions
- Use a cleaned dataset (your own from Module 3, or the Titanic dataset).
- Open it in a Jupyter Notebook or Google Colab.
- Build a visual narrative with 3โ4 charts:
- A context chart showing the big picture (e.g., distribution of the target variable).
- One or more exploratory charts showing relationships or subgroup patterns.
- A conclusion chart that supports your main takeaway.
- Each chart must include:
- A title that states the finding (not just the variable name).
- Labeled axes with units.
- A caption or short description beneath it.
- Add a short paragraph (3โ5 sentences) explaining the narrative as a whole.
- Bonus: Create a misleading version of one chart and explain what makes it misleading.
Submission
Your Jupyter Notebook with all charts + the narrative paragraph.
Assessment for Module 5
- Quiz (10 questions): Covers chart types, design principles, and misleading visualizations.
- Lab: Graded on chart correctness, design quality, and clarity of the narrative.
- Participation: Contribution to the group activity and discussion prompts.
Key Terms
- Data visualization โ turning data into visual form for understanding.
- matplotlib โ Python's foundational plotting library.
- seaborn โ a higher-level plotting library built on matplotlib.
- Bar chart โ compares categories with rectangular bars.
- Line chart โ shows change over time with connected points.
- Scatter plot โ shows relationships between two numeric variables.
- Histogram โ shows the distribution of one numeric variable.
- Box plot โ shows distribution, median, quartiles, and outliers.
- Heatmap โ uses color to show values in a matrix.
- Cut-off y-axis โ a misleading chart technique that exaggerates differences.
- Visual narrative โ a sequence of charts that tells a story.
Discussion Prompts
- Why are charts often more effective than tables for communicating findings?
- What's the danger of using a pie chart with many slices?
- When might a cut-off y-axis be legitimate (if ever)?
- What's the difference between a chart that's decorative and one that's informative?
- Can you think of a chart you've seen recently (in the news, on social media) that was misleading? What made it so?
Further Reading
- Cole Nussbaumer Knaflic, Storytelling with Data
- Edward Tufte, The Visual Display of Quantitative Information
- Alberto Cairo, The Truthful Art
- matplotlib and seaborn official documentation
- Kaggle Learn: "Data Visualization" micro-course
- Financial Times Visual Vocabulary โ a guide to choosing chart types
๐ก Instructor Note: Visualization is where data science becomes
communicable. Many students can compute statistics but struggle to present them
clearly. Emphasize that good visualization requires iteration โ the first chart is almost never
the best chart. Encourage students to critique each other's charts using the principles from
Lesson 4.