Data Visualization with Matplotlib & Pandas: Fundamentals & Practice
Data visualization is one of the foundational skill sets in data science and machine learning. Translating raw tabular data into intuitive visual figures makes complex patterns, distributions, correlations, and outliers immediately understandable.
This note documents core concepts, code structures, and best practices for creating static figures using Matplotlib and Pandas.
💡 Key Architectural Concepts in Matplotlib
Matplotlib uses an object-oriented API structure composed of two primary objects:
Figure(fig): The overarching canvas or container that holds all visual elements (axes, titles, legends, colorbars).Axes(ax): An individual subplot or chart area containing the x-axis, y-axis, plot elements (lines, bars, scatter points), labels, and gridlines.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Object-oriented figure and axes creation
fig, ax = plt.subplots(figsize=(8, 4.5), dpi=100)
# Customize the canvas
ax.set_title("Sample Visual Hierarchy", fontsize=14, fontweight="bold")
ax.set_xlabel("X Axis (Units)")
ax.set_ylabel("Y Axis (Units)")
ax.grid(True, linestyle="--", alpha=0.5)
plt.tight_layout()
plt.show()
📊 Essential Chart Types & Use Cases
| Chart Type | Primary Use Case | Key Function |
| :--- | :--- | :--- |
| Line Plot | Time series trends, continuous trends | ax.plot(x, y) |
| Bar Chart | Categorical comparisons, discrete metrics | ax.bar(categories, values) |
| Histogram | Numerical frequency distributions | ax.hist(data, bins=20) |
| Scatter Plot | Bivariate correlation & outlier detection | ax.scatter(x, y) |
| Box Plot | Quartiles, median, and statistical range | ax.boxplot(data) |
📈 Multi-Panel Subplots Pattern
Creating multi-panel subplots allows side-by-side comparison of different metrics or subsets of data:
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))
# Subplot 1: Distribution
axes[0].hist(np.random.randn(1000), bins=30, color="#3b82f6", edgecolor="black")
axes[0].set_title("Gaussian Distribution")
# Subplot 2: Correlation Scatter
x = np.linspace(0, 10, 50)
y = 2 * x + np.random.randn(50) * 2
axes[1].scatter(x, y, color="#ef4444", alpha=0.7)
axes[1].set_title("Bivariate Relationship")
plt.tight_layout()
🎯 Direct Integration with Pandas DataFrames
Pandas provides convenient wrapper methods (df.plot()) built directly on top of Matplotlib:
# Sample DataFrame
df = pd.DataFrame({
'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
'Revenue': [120, 150, 170, 210],
'Expenses': [90, 110, 125, 140]
})
# Pandas plot delegation to Matplotlib axes
ax = df.plot(x='Quarter', y=['Revenue', 'Expenses'], kind='bar', figsize=(8, 5))
ax.set_title("Quarterly Financial Breakdown")
ax.set_ylabel("USD (Thousands)")
plt.xticks(rotation=0)
plt.show()
🔗 Related Resources & Capstone Project
- Capstone Repository: [[data-visualization-mastery]] (Data Visualization Mastery Capstone)
- Prerequisites: See previous notes on [[python/pandas-data-analysis-mastery]] and [[python/all-about-numpy-array-computing]].
- Applied Computer Vision: [[live-with-paws]] and [[python/machine-learning-model-evaluation]].