Chapter 13A: Data Visualization with Matplotlib & Seaborn

Learning Objectives: By the end of this chapter, you will be able to:

13A.1 Introduction to Matplotlib

Matplotlib is Python's fundamental plotting library that provides:

13A.1.1 Basic Plotting

import matplotlib.pyplot as plt

# Create simple line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()
Simple Line Plot

Figure 1: Basic line plot example

13A.1.2 Multiple Plots in One Figure

# Create figure with subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

# First subplot
ax1.plot(x, y, 'r--')
ax1.set_title('Red Dashed Line')

# Second subplot
ax2.bar(x, y, color='g')
ax2.set_title('Green Bars')

plt.tight_layout()
plt.show()

13A.2 Common Plot Types

13A.2.1 Bar Charts

categories = ['A', 'B', 'C', 'D']
values = [15, 25, 30, 20]

plt.bar(categories, values, color=['red', 'green', 'blue', 'cyan'])
plt.title('Bar Chart Example')
plt.show()

13A.2.2 Histograms

import numpy as np

data = np.random.normal(0, 1, 1000)
plt.hist(data, bins=30, edgecolor='black')
plt.title('Histogram of Normal Distribution')
plt.show()

13A.2.3 Scatter Plots

x = np.random.rand(50)
y = x + np.random.normal(0, 0.1, 50)

plt.scatter(x, y, c='purple', alpha=0.7)
plt.title('Scatter Plot with Transparency')
plt.show()

13A.3 Introduction to Seaborn

Seaborn is a statistical visualization library built on Matplotlib that provides:

13A.3.1 Basic Seaborn Plots

import seaborn as sns

# Load example dataset
tips = sns.load_dataset('tips')

# Create a boxplot
sns.boxplot(x='day', y='total_bill', data=tips)
plt.title('Boxplot of Total Bill by Day')
plt.show()
Seaborn Boxplot

Figure 2: Seaborn boxplot example

13A.3.2 Advanced Seaborn Visualizations

# Pair plot for multivariate analysis
sns.pairplot(tips, hue='sex', palette='husl')
plt.show()

# Heatmap for correlation matrix
corr = tips.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title('Correlation Heatmap')
plt.show()

13A.4 Customizing Plots

# Create a customized plot
plt.figure(figsize=(8, 6))
sns.set_style('whitegrid')

ax = sns.barplot(x='day', y='total_bill', data=tips, 
                 palette='viridis', ci=None)

ax.set_title('Average Bill by Day', fontsize=16)
ax.set_xlabel('Day of Week', fontsize=12)
ax.set_ylabel('Average Bill ($)', fontsize=12)

# Add value labels
for p in ax.patches:
    ax.annotate(f"{p.get_height():.2f}", 
                (p.get_x() + p.get_width() / 2., p.get_height()),
                ha='center', va='center', xytext=(0, 10), 
                textcoords='offset points')

plt.tight_layout()
plt.savefig('custom_plot.png', dpi=300)
plt.show()
Exercise:
  1. Create a line plot showing the growth of $100 invested at 7% annual interest over 30 years
  2. Using the 'tips' dataset from Seaborn:
    • Create a violin plot showing total bill distribution by day and time
    • Make a scatter plot of total bill vs tip with points colored by smoker status
    • Customize one of your plots with titles, labels, and a custom color palette
Key Takeaways: