Data Visualization with Matplotlib
Turning numbers into pictures
📖 Concept Recap
matplotlib is Python’s foundational plotting library.
- Figure & Axes:
fig, ax = plt.subplots(figsize=(8, 5)) - Chart types:
ax.bar(),ax.plot(),ax.scatter(),ax.hist() - Labels:
ax.set_title(),ax.set_xlabel(),ax.set_ylabel() - Legend: add
label=to each plot call, thenax.legend() - Multiple panels:
fig, axes = plt.subplots(2, 2, figsize=(12, 8)) - Always call:
plt.tight_layout()beforeplt.show()to prevent overlap - In this browser lab: include
matplotlib.use('Agg')at the top of every code block
👀 Worked Example
A labeled bar chart — run this to see matplotlib in action:
Exercise 1 — Monthly Sales Line Chart
Complete the line chart by filling in the blanks. Add a marker symbol and titles.
's' (square), '^' (triangle), 'D' (diamond). Title and ylabel should be descriptive strings in quotes.Exercise 2 — Study Hours vs. Exam Scores
Create a scatter plot for 10 students. Make up realistic data for hours studied (2–10) and exam scores (40–100). Color the dots by pass/fail (score ≥ 60 = green pass, red fail). Add axis labels and a title.
ax.scatter(study_hours, exam_scores, c=colors, s=100, alpha=0.8). Add a horizontal line at y=60 with ax.axhline(60, color='gray', linestyle='--', alpha=0.5, label='Pass line').Exercise 3 — 2×2 Dashboard
Create a 2×2 subplot grid with four different chart types:
- Top-left: Bar chart — monthly sales by category (Electronics, Clothing, Food)
- Top-right: Line chart — monthly revenue trend over 6 months
- Bottom-left: Histogram — distribution of test scores (use:
[72,85,91,68,77,83,90,64,88,75,79,82,95,71,86,69,93,78,84,73]) - Bottom-right: Horizontal bar chart — top 5 products by sales
ax2.plot(months, revenue, marker='o', color='#1565C0'). Histogram: ax3.hist(scores, bins=6, color='#6A1B9A', edgecolor='white'). Horizontal bar: ax4.barh(products, prod_sales).Mini Project — Q1 Management Report
You are presenting Q1 results to management. Create a professional 2-row figure:
- Top (full width): Line chart of weekly revenue for 12 weeks (make up the data — include a realistic dip and recovery)
- Bottom-left: Bar chart of revenue by region (West, East, South, North)
- Bottom-right: A text summary box using
ax.text()showing: Total Revenue, Best Week, Top Region, Weeks Above Average
Use plt.subplots(2, 2) and merge the top row with fig.add_subplot(2, 1, 1) approach, or use gridspec. Consistent colors and proper labels required.
✅ Lab 9 Complete!
You’ve built bar charts, line charts, scatter plots, histograms, multi-panel dashboards, and a full management report. Visualization is the final step that makes your analysis communicable.
Continue to Lab 10: Capstone Project →