You're observing that your code runs correctly without explicitly creating a figure object, and you're wondering why it doesn't produce an error. The reason lies in how Matplotlib's pyplot interface handles figure and axes creation.
Automatic Figure Creation in Matplotlib
Matplotlib's pyplot module is designed to mimic MATLAB's plotting behavior, where figures and axes are managed implicitly. When you use commands like plt.subplot(), plt.plot(), plt.scatter(), etc., pyplot automatically handles the creation of figures and axes if they don't already exist.
Here's what's happening in your code:
import matplotlib.pyplot as plt
ax1 = plt.subplot(2, 2, 1)
ax1.plot([1, 2, 3], [3, 2, 1])
ax2 = plt.subplot(2, 2, 2)
ax2.scatter([1, 2, 3], [3, 2, 1])
ax3 = plt.subplot(2, 1, 2)
ax3.vlines(1, 0, 1)
plt.show()
-
plt.subplot(2, 2, 1):
- If there is no current figure,
pyplot automatically creates one.
- It then adds a subplot (an
Axes object) to this figure.
-
Plotting commands (ax1.plot, ax2.scatter, etc.):
- These methods modify the axes returned by
plt.subplot().
-
No Explicit Figure Creation:
- Since
pyplot handles figure creation implicitly, your code doesn't throw an error even without fig = plt.figure().
When to Use Explicit Figure Creation
While pyplot can manage figures and axes for simple plots, there are times when you might want to create figures explicitly:
- Figure Customization: Setting the figure size, DPI, background color, etc.
- Multiple Figures: Managing more than one figure at a time.
- Object-Oriented Approach: For more complex plots, it's often clearer to work directly with
Figure and Axes objects.
Your second code snippet illustrates explicit figure creation:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
fig = plt.figure(figsize=(6, 4))
plt.subplot(221)
plt.plot(x, np.sin(x))
plt.subplot(222)
plt.plot(x, np.cos(x))
plt.subplot(212)
plt.plot(x, np.tan(x))
plt.show()
fig = plt.figure(figsize=(6, 4)):
- Explicitly creates a figure with a specified size.
- Subsequent
plt.subplot() and plt.plot() commands add to this figure.
Understanding plt.subplot()
The plt.subplot() function can be used in two ways:
-
Creating Subplots in a Grid:
- Syntax:
plt.subplot(nrows, ncols, index)
- Creates a subplot in a grid layout.
- Example:
plt.subplot(2, 2, 1) creates a subplot in the first position of a 2x2 grid.
-
Returning an Axes Object:
- When called,
plt.subplot() returns an Axes object.
- Assigning this to a variable (e.g.,
ax1 = plt.subplot(...)) allows you to manipulate the axes directly.
Summary
Example of Object-Oriented Approach
Here's how you might rewrite your first code using explicit figure and axes creation:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2) # Creates a 2x2 grid of subplots
axs[0, 0].plot([1, 2, 3], [3, 2, 1])
axs[0, 1].scatter([1, 2, 3], [3, 2, 1])
# For the subplot that spans the second row
# Remove the unused axis and create a new one that spans both columns
fig.delaxes(axs[1, 0])
fig.delaxes(axs[1, 1])
ax_large = fig.add_subplot(2, 1, 2)
ax_large.vlines(1, 0, 1)
plt.tight_layout()
plt.show()
- Advantages:
- More control over the layout.
- Clearer manipulation of individual axes.
Conclusion
Your code runs without error because Matplotlib's pyplot module is designed to handle figure and axes creation automatically when needed. This behavior allows for quick and easy plotting without the overhead of managing figure objects explicitly. However, understanding when and how to create figures and axes explicitly is valuable for producing more complex and customized visualizations.