Introduction
Matplotlib is the foundational plotting library for Python, enabling creation of a wide variety of charts.
Basic Plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("Sine Wave")
plt.show()
Multiple Plots
# Subplots
fig, axes = plt.subplots(2, 2)
axes[0, 0].plot(x, y)
axes[0, 1].plot(x, np.cos(x))
axes[1, 0].plot(x, np.tan(x))
axes[1, 1].plot(x, x**2)
plt.tight_layout()
plt.show()
Chart Types
# Line plot
plt.plot(x, y)
# Scatter plot
plt.scatter(x, y)
# Bar plot
plt.bar(x, y)
# Histogram
plt.hist(data, bins=30)
# Pie chart
plt.pie(values, labels=labels)
Practice Problems
- Create line plot of stock prices
- Build scatter plot with different markers
- Compare multiple line charts
- Add legends and annotations
- Customize colors and styles