5 Best Ways to Plot Multiple Graphs in a Single Figure with Matplotlib and Python

Rate this post

πŸ’‘ Problem Formulation: When analyzing data, it’s often helpful to compare multiple sets of data side by side. With Python’s Matplotlib library, you can create a single figure containing multiple plots. This article will explore how to achieve this, covering methods from basic subplotting to advanced layout managers. Imagine needing to visualize separate temperature trends for different cities on one figure; these methods will show you how.

Method 1: Using subplot()

Matplotlib’s subplot() function allows you to add multiple plots to a figure by creating a grid and specifying the plot’s position within that grid. It’s simple and effective for arranging plots in a structured layout.

Here’s an example:

import matplotlib.pyplot as plt

# Create a figure and a grid of subplots
fig, ax = plt.subplots(2, 2)

# Plot data in each subplot
ax[0, 0].plot([1, 2, 3], [1, 4, 9])
ax[0, 1].plot([1, 2, 3], [1, 2, 3])
ax[1, 0].plot([1, 2, 3], [3, 2, 1])
ax[1, 1].plot([1, 2, 3], [9, 4, 1])

# Show the figure
plt.show()

The output is a figure with four subplots arranged in a 2×2 grid, each containing a different plot.

This code creates a figure and a 2×2 grid of axes (plots), then plots different data on each axis. It’s a straightforward way of comparing datasets directly.

Method 2: Using subplot2grid()

For more control over the layout when placing subplots, the subplot2grid() function is quite flexible. It can create subplots that span multiple rows or columns in a grid, perfect for custom layouts.

Here’s an example:

import matplotlib.pyplot as plt

# Create a 3x3 grid and position the subplots
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2)
ax2 = plt.subplot2grid((3, 3), (0, 2), rowspan=3)
ax3 = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2)

# Plot data in each subplot
ax1.plot([1,2,3], [2,3,5])
ax2.plot([1,2,3], [5,7,8])
ax3.plot([1,2,3], [3,2,1])

# Show the figure
plt.show()

The output shows a figure with three subplots of various sizes and positions, demonstrating a customized layout.

We used subplot2grid() to create a more complex layout that spans rows and columns. This method is great when you need certain plots to be larger or differently aligned compared to others.

Method 3: Using GridSpec

The GridSpec module from Matplotlib provides an even more advanced interface for creating complex subplot layouts. You can specify each subplot’s size with much finer granularity than subplot2grid().

Here’s an example:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

# Create a GridSpec layout
gs = GridSpec(3, 3)

# Create subplots using the GridSpec layout
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, :-1])
ax3 = fig.add_subplot(gs[1:, 2])
ax4 = fig.add_subplot(gs[2, 0])
ax5 = fig.add_subplot(gs[2, 1])

# Plot data in each subplot
ax1.plot(...)
ax2.plot(...)
ax3.plot(...)
# ... Additional plotting commands

# Show the figure
plt.show()

The output will display a complex layout consisting of multiple plots of varying sizes, precisely arranged according to the specified GridSpec.

By defining a GridSpec and adding subplots to the figure with precise grid positions, you gain fine control over the layout and sizing of each subplot. It’s a powerful tool for designing intricate figure layouts.

Method 4: Using add_axes()

The add_axes() method gives you explicit control by defining the exact position and size of the subplot in the figure coordinates. This is useful when you need precise placement of your plots.

Here’s an example:

import matplotlib.pyplot as plt

# Create a figure
fig = plt.figure()

# Specify the geometry of the subplots
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.4])  # left, bottom, width, height
ax2 = fig.add_axes([0.5, 0.6, 0.4, 0.3])

# Plot data in each subplot
ax1.plot([1, 2, 3], [2, 4, 3])
ax2.plot([1, 2, 3], [5, 3, 6])

# Show the figure
plt.show()

The output will show two subplots with custom positions and sizes relative to the figure.

This snippet directly places two axes on the figure canvas using a list of coordinates that represent the left, bottom, width, and height of the subplot area in figure coordinates. This manual placement is highly specific and useful when precise control is required.

Bonus One-Liner Method 5: Using plot() for simple overlays

For quickly overlaying multiple datasets, calling plot() repeatedly on the same axes object is the simplest approach. It’s best for comparing multiple data sets directly on top of each other.

Here’s an example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [2, 4, 3])
plt.plot([1, 2, 3], [3, 2, 1])
plt.show()

The output is a single plot with two datasets overlaid on each other.

Overlaying plots is as simple as calling plot() several times before calling show(). It’s great for a quick comparison, but can get cluttered with many datasets.

Summary/Discussion

  • Method 1: Using subplot(). Best for regular grids of subplots. Not ideal for irregular layouts.
  • Method 2: Using subplot2grid(). Offers more customization than subplot() but still limited by the grid.
  • Method 3: Using GridSpec. Highly customizable and can handle complex layouts, but has a steeper learning curve.
  • Method 4: Using add_axes(). Provides pixel-perfect control, yet can be tedious for simple layouts.
  • Bonus Method 5: Simple plot() overlays. Quick and easy but can become unreadable with too many overlays.