5 Best Ways to Combine Multiple Graphs in Python

💡 Problem Formulation: When working with data visualization in Python, a common challenge is combining multiple graphs into a single figure for comparative analysis or comprehensive presentations. Whether you’re looking to overlay line charts, juxtapose bar graphs, or create multi-panel plots, finding the right method to unite them cohesively is key. Users seek a solution for inputting several individual plots and obtaining a unified graphical representation as their output.

Method 1: Using Matplotlib’s Subplots

Matplotlib’s subplots() function provides a flexible way to create a figure with a grid of subplots. You can define the number of rows and columns to organize multiple graphs in a structured manner. Each subplot can contain a different graph, and they share a common axis label to maintain cohesion. This method is highly customizable and great for comparing similar datasets.

Here’s an example:

import matplotlib.pyplot as plt

# Create a figure with 2x1 grid of subplots
fig, axes = plt.subplots(2, 1)

# Plot data on the first subplot
axes[0].plot([1,2,3], [4,5,6])

# Plot data on the second subplot
axes[1].plot([4,5,6], [1,2,3])

# Display the figure
plt.show()

The output is a figure with two vertically aligned graphs.

This code snippet sets up a figure with two subplots stacked vertically. The line plt.subplots(2, 1) creates a figure and a 2×1 grid of subplots. The first subplot at the top is accessed with axes[0] and the second subplot below it with axes[1]. Each plot function draws a simple line graph on its respective subplot, and plt.show() visually renders the combined figure.

Method 2: Using Seaborn’s FacetGrid

Seaborn is a statistical plotting library built on Matplotlib. FacetGrid is one of Seaborn’s powerful features for generating a grid of plots based on the values of one or more categorical variables. It’s effective for creating complex multi-plot grids when you want to condition on different dataset features.

Here’s an example:

import seaborn as sns
import matplotlib.pyplot as plt

# Load an example dataset
tips = sns.load_dataset('tips')

# Create a grid of plots conditioned on 'time' variable
g = sns.FacetGrid(tips, col='time')
g.map(plt.hist, 'total_bill')

# Show the plots
plt.show()

The output is a figure with separate histograms for ‘Lunch’ and ‘Dinner’.

After importing Seaborn and loading the ‘tips’ dataset, we use FacetGrid() to create a grid of histograms. The col='time' argument specifies the variable for conditioning, creating multiple subplots. g.map() applies the plotting function to each subset of the data, effectively separating the total bill amounts into lunch and dinner time slots, depicted in individual histograms.

Method 3: Using Pandas Plotting

Pandas, Python’s premier data manipulation library, integrates with Matplotlib to offer direct plotting from DataFrames. Using the plot() method with the subplots=True argument can quickly generate multiple graphs for different DataFrame columns, each in their own subplot, making it superbly convenient for quick analysis.

Here’s an example:

import pandas as pd
import numpy as np

# Construct a DataFrame with random data
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

# Plot each DataFrame column as a separate subplot
axes = df.plot(subplots=True)

# Show the plots
plt.show()

The output is four separate line graphs, one for each column of the DataFrame.

This snippet starts with the creation of a simple DataFrame df containing random numbers. Invoking the plot() method with subplots=True instructs pandas to draw each column in the DataFrame as a distinct line graph in separate subplots. These are automatically arranged in a grid and displayed with plt.show().

Method 4: Using Plotly’s Subplots

Plotly is an interactive graphing library, and its subplots feature allows creating customizable and interactive multi-plot layouts. Plotly subplots enable not only the combination of multiple plots but also the incorporation of different chart types within the same figure.

Here’s an example:

from plotly.subplots import make_subplots
import plotly.graph_objs as go

# Initialize a figure with a 1x2 subplot layout
fig = make_subplots(rows=1, cols=2)

# Add a scatter plot to the first column
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)

# Add a bar chart to the second column
fig.add_trace(go.Bar(x=[1, 2, 3], y=[6, 5, 4]), row=1, col=2)

# Show the figure
fig.show()

The output is an interactive figure with a scatter plot on the left and a bar chart on the right.

By using Plotly’s make_subplots() function, we establish a 1×2 subplot grid. Two traces are then added to the figure: a Scatter() trace and a Bar() trace, which are positioned into the first row, first column, and first row, second column, respectively. fig.show() displays the interactive figure in a web browser.

Bonus One-Liner Method 5: Stacked Plots with pyplot

In situations where simplicity is needed, Matplotlib’s pyplot interface allows stacking of multiple plots with a one-liner using the plot() method multiple times before calling show().

Here’s an example:

import matplotlib.pyplot as plt

# Plot multiple lines on the same axes
plt.plot([1, 2, 3], [4, 5, 6])
plt.plot([1, 2, 3], [6, 5, 4])

# Show the combined plot
plt.show()

The output is a single graph with two overlapping line plots.

This is the simplest method to combine multiple plots. We call plt.plot() twice, each time passing a different dataset. Matplotlib overlays the second plot on top of the first on the same set of axes. Once all desired plots are added, plt.show() is used to display the combined plot.

Summary/Discussion

  • Method 1: Using Matplotlib’s Subplots. Offers granular control over the layout of multiple graphs. Strengths: highly customizable, efficient for similar datasets. Weaknesses: may become complex with a large number of subplots.
  • Method 2: Using Seaborn’s FacetGrid. Best for creating a cohesive set of plots based on categorical data. Strengths: streamlined for statistical comparison. Weaknesses: less flexibility compared to Matplotlib for non-statistical tasks.
  • Method 3: Using Pandas Plotting. Convenient for quick exploratory data analysis directly from DataFrames. Strengths: easy to use and quick to implement. Weaknesses: depends on Matplotlib’s backend, which may limit interactivity.
  • Method 4: Using Plotly’s Subplots. Ideal for creating interactive, web-friendly visualizations. Strengths: interactive graphs, integration of different types of plots. Weaknesses: bit steeper learning curve and requires internet connection for full features.
  • Bonus Method 5: Stacked Plots with pyplot. Quick and easy stacking of graphs in one line. Strengths: simplest method for combining plots. Weaknesses: limited control over individual plot aesthetics and arrangement.