Getting Started with Matplotlib
Getting Started with Matplotlib
Matplotlib is Python's most widely used plotting library. In this lesson, you'll learn how to import Matplotlib, understand its structure, and create your first plots.
Importing Matplotlib
The most common way to import Matplotlib is using the pyplot module with the alias plt:
The pyplot module provides a MATLAB-like interface for creating plots quickly. Let's break down what happened:
import matplotlib.pyplot as plt- Imports the plotting moduleplt.plot(x, y)- Creates a line plotplt.show()- Displays the plot
The Two Interfaces
Matplotlib offers two ways to create plots:
1. Pyplot Interface (Stateful)
Quick and simple, good for simple plots:
2. Object-Oriented Interface
More control, better for complex plots:
We'll primarily use the object-oriented approach in this course because:
- It's more explicit and readable
- It scales better for complex visualizations
- It's the recommended approach for production code
Understanding Figure Size
The figsize parameter controls the size of your plot in inches:
Basic Plot Elements
Every plot has several key elements:
Creating Multiple Plots
You can create multiple plots in one figure:
Saving Plots
To save your plot to a file, use savefig():
Practice: Your First Custom Plot
Key Takeaways
- Import Matplotlib with
import matplotlib.pyplot as plt - Use
plt.subplots()to create figures and axes (object-oriented approach) - Control figure size with
figsize=(width, height)in inches - Add titles with
ax.set_title(), labels withax.set_xlabel()andax.set_ylabel() - Add grids with
ax.grid(True)and legends withax.legend() - Save plots with
fig.savefig('filename.png', dpi=300) - Always call
plt.show()to display plots (orplt.tight_layout()before showing)
In the next lesson, we'll dive deeper into the Figure and Axes objects that form the core of Matplotlib.

