<<–2/”>a href=”https://exam.pscnotes.com/5653-2/”>p>plt.subplots()
and plt.figure()
in Matplotlib.
Introduction
Matplotlib is Python’s powerful data visualization library. At its core, creating plots involves figures and axes.
- Figure: The top-level container, like a canvas, holding everything you see in your plot (axes, titles, labels, etc.).
- Axes: The specific area within the figure where your data is plotted. You can have multiple axes within a figure for creating subplots.
plt.figure()
and plt.subplots()
are the primary functions for creating these Elements, each with its own approach.
Key Differences: A Tabular Comparison
Feature | plt.figure() | plt.subplots() |
---|---|---|
Purpose | Creates a new figure object (an empty canvas). | Creates a figure and a grid of subplots (axes) in one go. |
Return Value | A single figure object. | A tuple containing: (1) a figure object, (2) an array of axes objects. |
Usage | More manual control over figure layout and adding individual axes. | Streamlined for quickly generating multiple plots in a grid layout. |
Example | fig = plt.figure() ax = fig.add_subplot(111) | fig, axs = plt.subplots(2, 2) |
Advantages and Disadvantages
Function | Advantages | Disadvantages |
---|---|---|
plt.figure() | – Fine-grained control over figure size, aspect ratio, etc. – Ideal for complex layouts or single plots. | – More verbose for simple scenarios. – Requires extra steps to add axes. |
plt.subplots() | – Convenient for creating subplots in a grid. – Concise syntax. – Automatically handles axes placement. | – Less flexible for complex or irregular subplot arrangements. |
Similarities
- Both functions are used for creating the foundation of Matplotlib plots.
- Both accept keyword arguments for customizing figure properties (e.g.,
figsize
,dpi
). - Ultimately, both work with the same underlying figure and axes objects.
Frequently Asked Questions (FAQs)
Which is better to use,
plt.figure()
orplt.subplots()
?
It depends on your needs. If you need a single plot or a complex layout,plt.figure()
might be better. For quick subplot grids,plt.subplots()
is ideal.Can I mix
plt.figure()
andplt.subplots()
in the same script?
You can create figures withplt.figure()
and then add axes fromplt.subplots()
(or vice-versa) as needed.What’s the difference between
plt.subplot()
andplt.subplots()
?
Note the ‘s’ at the end.plt.subplot()
is used for adding a single subplot to an existing figure, whileplt.subplots()
creates a figure and a grid of subplots simultaneously.
Detailed Example: Combining Both Approaches
import matplotlib.pyplot as plt
import numpy as np
# Create a figure with custom size and dpi
fig = plt.figure(figsize=(10, 8), dpi=100)
# Add a subplot using GridSpec for more control over layout
gs = fig.add_gridspec(2, 2, width_ratios=[3, 1], height_ratios=[1, 2])
# Create subplots in different positions
ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, 0])
ax3 = fig.add_subplot(gs[1, 1])
# Use subplots() for a simple 2x1 grid
fig2, axs = plt.subplots(2, 1, figsize=(6, 6))
# Plot some data on all axes
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
ax1.plot(x, y, label='Sine')
ax2.scatter(x, y, label='Scatter')
ax3.bar(x, y, label='Bar')
axs[0].plot(x, np.cos(x), label='Cosine')
axs[1].plot(x, np.tan(x), label='Tangent')
# Add labels and titles
ax1.set_title('Custom Layout with plt.figure()')
fig2.suptitle('Simple Grid with plt.subplots()')
# Add legends to all subplots
for ax in [ax1, ax2, ax3, axs[0], axs[1]]:
ax.legend()
plt.show()
Let me know if you’d like any of these aspects explored in more detail!