Matplotlib – Difference between plt.subplots() and plt.figure()

In Matplotlib, plt.figure() and plt.subplots() are two fundamental functions for creating plots, but they serve different purposes and return different objects.

Understanding plt.figure()

plt.figure() creates a new figure object or activates an existing one. It returns a Figure object but doesn't create any axes by default.

import matplotlib.pyplot as plt
import numpy as np

# Create a figure using plt.figure()
fig = plt.figure(figsize=(8, 5))
fig.suptitle("Using plt.figure()")

# Add data manually using plt.plot()
x = np.linspace(0, 10, 50)
y = np.sin(x)
plt.plot(x, y, 'b-', label='sin(x)')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()
plt.grid(True)

plt.show()
[Displays a sine wave plot with the title "Using plt.figure()"]

Understanding plt.subplots()

plt.subplots() creates both a figure and a set of subplots in one call. It returns both the Figure object and Axes object(s).

import matplotlib.pyplot as plt
import numpy as np

# Create figure and axes using plt.subplots()
fig, ax = plt.subplots(figsize=(8, 5))
fig.suptitle("Using plt.subplots()")

# Add data using the axes object
x = np.linspace(0, 10, 50)
y = np.cos(x)
ax.plot(x, y, 'r-', label='cos(x)')
ax.set_xlabel('X values')
ax.set_ylabel('Y values')
ax.legend()
ax.grid(True)

plt.show()
[Displays a cosine wave plot with the title "Using plt.subplots()"]

Creating Multiple Subplots

The real power of plt.subplots() becomes evident when creating multiple subplots ?

import matplotlib.pyplot as plt
import numpy as np

# Create figure with multiple subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
fig.suptitle("Multiple Subplots using plt.subplots()")

x = np.linspace(0, 10, 50)

# First subplot
ax1.plot(x, np.sin(x), 'b-')
ax1.set_title('sin(x)')
ax1.grid(True)

# Second subplot
ax2.plot(x, np.cos(x), 'r-')
ax2.set_title('cos(x)')
ax2.grid(True)

plt.tight_layout()
plt.show()
[Displays two side-by-side plots showing sin(x) and cos(x)]

Comparison

Aspect plt.figure() plt.subplots()
Returns Figure object only Figure and Axes objects
Axes Creation Manual (using plt.subplot()) Automatic
Multiple Subplots Requires additional calls Created in one call
Best For Simple single plots Structured subplot layouts

When to Use Which?

Use plt.figure() when you need a simple figure and plan to use pyplot-style plotting commands. Use plt.subplots() when you want object-oriented plotting or need multiple subplots with better control over layout.

Conclusion

plt.subplots() provides better control and cleaner code structure, especially for complex layouts. plt.figure() is simpler for basic single plots using pyplot interface.

Updated on: 2026-03-26T15:22:48+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements