Course contentsShow
← Data Science
Lesson 1256 of 2,14532. Visualization with Matplotlib and SeabornFree lesson

Two Interfaces: pyplot vs Object-Oriented

Comparing plt.plot() style (pyplot) with fig, ax = plt.subplots() (OO) and when to use each approach.

Two Interfaces: pyplot vs Object-Oriented

You'll learn the two primary ways to create plots in Matplotlib and when to use each approach.

Matplotlib offers two distinct interfaces for creating visualizations, and understanding both helps you write clearer, more maintainable code.

The pyplot Interface (State-Based)

The pyplot interface uses plt.plot(), plt.xlabel(), and similar functions. It's inspired by MATLAB and works by modifying the "current" figure and axes automatically. Think of it like using voice commands: "Add a line," "Change the title," "Make it blue"—Matplotlib keeps track of what you're currently working on.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X Label')
plt.title('My Plot')
plt.show()

This approach is quick and intuitive for simple, single plots—perfect for exploratory analysis when you need fast results.

The Object-Oriented Interface (Explicit)

The object-oriented (OO) interface uses fig, ax = plt.subplots() to explicitly create figure and axes objects. You then call methods on those objects directly. It's like getting handles to specific canvases and painting on them deliberately.

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_xlabel('X Label')
ax.set_title('My Plot')
plt.show()

This approach gives you precise control, especially when creating multiple subplots or building complex visualizations. You always know exactly which axes you're modifying.

When to Use Each

  • Use pyplot for quick exploratory visualizations and simple single plots
  • Use OO interface for production code, complex layouts, multiple subplots, or when functions need to accept specific axes to plot on

Key Takeaway: Matplotlib's pyplot interface (plt.plot()) is convenient for quick exploration, while the object-oriented interface (fig, ax = plt.subplots()) provides explicit control needed for complex, reproducible visualizations.