Difference between Plt subplots and plt figure

<<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

Featureplt.figure()plt.subplots()
PurposeCreates a new figure object (an empty canvas).Creates a figure and a grid of subplots (axes) in one go.
Return ValueA single figure object.A tuple containing: (1) a figure object, (2) an array of axes objects.
UsageMore manual control over figure layout and adding individual axes.Streamlined for quickly generating multiple plots in a grid layout.
Examplefig = plt.figure()
ax = fig.add_subplot(111)
fig, axs = plt.subplots(2, 2)

Advantages and Disadvantages

FunctionAdvantagesDisadvantages
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)

  1. Which is better to use, plt.figure() or plt.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.

  2. Can I mix plt.figure() and plt.subplots() in the same script?
    You can create figures with plt.figure() and then add axes from plt.subplots() (or vice-versa) as needed.

  3. What’s the difference between plt.subplot() and plt.subplots()?
    Note the ‘s’ at the end. plt.subplot() is used for adding a single subplot to an existing figure, while plt.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!