Skip to main content

10.3 - Data Visualization with Matplotlib & Seaborn

Theory 25 min Advanced

Matplotlib Basics

import matplotlib.pyplot as plt
import numpy as np

# Line plot
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y, color="blue", linewidth=2, label="sin(x)")
ax.plot(x, np.cos(x), color="red", linestyle="--", label="cos(x)")
ax.set_title("Trigonometric Functions")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("trig.png", dpi=150)
plt.show()

Common Plot Types

# Bar chart
categories = ["A", "B", "C", "D"]
values = [25, 40, 30, 55]

fig, ax = plt.subplots()
bars = ax.bar(categories, values, color=["#3776AB", "#FFD43B", "#28a745", "#dc3545"])
ax.bar_label(bars) # add value labels
ax.set_title("Category Comparison")

# Histogram
data = np.random.randn(1000)
ax.hist(data, bins=30, color="steelblue", edgecolor="white", alpha=0.7)

# Scatter plot
x = np.random.rand(50)
y = x + np.random.normal(0, 0.1, 50)
ax.scatter(x, y, c="steelblue", alpha=0.6, edgecolors="white")

# Box plot
data = [np.random.normal(0, i, 100) for i in range(1, 4)]
ax.boxplot(data, labels=["Group 1", "Group 2", "Group 3"])

Multiple Subplots

fig, axes = plt.subplots(2, 2, figsize=(10, 8))

axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title("Sine")

axes[0, 1].hist(np.random.randn(500), bins=20)
axes[0, 1].set_title("Histogram")

axes[1, 0].scatter(np.random.rand(50), np.random.rand(50))
axes[1, 0].set_title("Scatter")

axes[1, 1].bar(["A","B","C"], [30,40,25])
axes[1, 1].set_title("Bar")

plt.tight_layout()
plt.savefig("dashboard.png")

Seaborn — Statistical Visualization

import seaborn as sns
import pandas as pd

# Built-in datasets
tips = sns.load_dataset("tips")

# Distribution
sns.histplot(tips["total_bill"], kde=True)

# Categorical
sns.boxplot(x="day", y="total_bill", data=tips)
sns.violinplot(x="day", y="total_bill", data=tips)
sns.barplot(x="day", y="tip", hue="sex", data=tips)

# Correlation
corr = tips.corr(numeric_only=True)
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm")

# Pair plots
sns.pairplot(tips, hue="sex")

Key Vocabulary

TermDefinition
fig, axFigure and Axes objects from plt.subplots()
ax.plot()Line chart
ax.bar()Bar chart
ax.hist()Histogram
ax.scatter()Scatter plot
snsSeaborn — statistical visualization library
sns.heatmap()Color-coded matrix — great for correlations
plt.tight_layout()Adjusts subplot spacing

Summary

  • fig, ax = plt.subplots() is the modern Matplotlib API
  • ax.plot(), ax.bar(), ax.hist(), ax.scatter() for common chart types
  • Always set title, labels, and legend for clarity
  • plt.subplots(rows, cols) creates a grid of charts
  • Seaborn builds on Matplotlib with statistical plots and better aesthetics
  • sns.heatmap(df.corr()) visualizes feature correlations instantly