Matplotlib Introduction
Matplotlib is the granddaddy of Python visualization libraries. Almost every other plotting library is built on top of it. It gives you complete control over every element of a chart — but that flexibility comes with a learning curve.
Your First Plot
Let's jump right in. The pyplot module gives you a MATLAB-like interface that's easy to get started with.
import matplotlib.pyplot as plt
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.show()
That's it — five lines to create a plot. The plt.show() command renders the plot. In Jupyter notebooks, you can also use %matplotlib inline to display plots automatically.
Figure and Axes
Under the hood, matplotlib has two main objects: Figure (the canvas) and Axes (the actual plot). Understanding this distinction helps you create more complex visualizations.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8, 5))
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)")
ax.set_title("Sin and Cos")
ax.legend()
plt.show()
Using the object-oriented approach (fig, ax = plt.subplots()) is recommended for anything beyond simple plots. It gives you explicit control over each axes.
Common Plot Types
Matplotlib supports dozens of plot types. Here are the ones you'll use most in data science.
import matplotlib.pyplot as plt
import numpy as np
categories = ["A", "B", "C", "D"]
values = [23, 45, 56, 78]
plt.bar(categories, values)
plt.title("Bar Chart")
plt.show()
data = np.random.randn(1000)
plt.hist(data, bins=30)
plt.title("Histogram")
plt.show()
Use .bar() for bar charts, .hist() for histograms, .scatter() for scatter plots, and .pie() for pie charts. Each has many customization options.
Key Takeaways
- Matplotlib is the foundation of Python visualization
- The object-oriented approach (fig, ax) gives more control
- plt.subplots() is the standard way to create figures
- Supports bar, line, scatter, histogram, and many more plot types