Jupyter Notebook Display Multiple Plots

7 min read Oct 08, 2024
Jupyter Notebook Display Multiple Plots

Displaying Multiple Plots in Jupyter Notebook

Jupyter Notebook is a powerful tool for data analysis and visualization. One of its most valuable features is the ability to display multiple plots within the same notebook. This allows for a comprehensive understanding of your data by comparing different visualizations side-by-side. Let's explore different methods to achieve this.

1. Using plt.figure and plt.subplot

This is the classic approach using Matplotlib, the foundational plotting library in Python. The key is to create a figure and divide it into subplots using plt.subplots().

Example:

import matplotlib.pyplot as plt
import numpy as np

# Create data for two plots
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create a figure with 2 subplots
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(8, 6))

# Plot first subplot
axes[0].plot(x, y1)
axes[0].set_title('Sine Wave')

# Plot second subplot
axes[1].plot(x, y2)
axes[1].set_title('Cosine Wave')

plt.tight_layout()
plt.show()

This code creates a figure with two rows and one column of subplots. You then use axes[0] and axes[1] to access individual subplots and plot your data.

2. Creating Subplots Within a Loop

If you need to create many plots, a loop can simplify the process.

Example:

import matplotlib.pyplot as plt
import numpy as np

# Data for multiple plots
data = [np.random.randn(100) for _ in range(5)]

# Create a figure with 5 subplots
fig, axes = plt.subplots(nrows=5, ncols=1, figsize=(8, 12))

# Loop to plot each dataset
for i, ax in enumerate(axes):
    ax.hist(data[i], bins=20)
    ax.set_title(f'Distribution {i+1}')

plt.tight_layout()
plt.show()

This example generates five histograms, each representing a different dataset.

3. Utilizing plt.subplot2grid for Flexible Layouts

For more complex layout arrangements, plt.subplot2grid provides granular control.

Example:

import matplotlib.pyplot as plt
import numpy as np

# Data for three plots
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Create a figure with a custom layout
fig = plt.figure(figsize=(8, 6))

# Plot sine and cosine in a 2x1 grid
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2, rowspan=2)
ax1.plot(x, y1, label='Sine')
ax1.plot(x, y2, label='Cosine')
ax1.legend()

# Plot tangent in the bottom row
ax2 = plt.subplot2grid((3, 3), (2, 0), colspan=3)
ax2.plot(x, y3, label='Tangent')
ax2.legend()

plt.tight_layout()
plt.show()

This code creates a 3x3 grid and places the first two plots in a 2x1 span, while the third plot occupies the entire bottom row.

4. Working with Seaborn for Attractive Plots

Seaborn, a high-level statistical plotting library, offers a more visually appealing approach.

Example:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# Sample data
df = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'group': np.random.choice(['A', 'B'], size=100)
})

# Create a figure with two subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))

# Scatter plot with hue
sns.scatterplot(x='x', y='y', hue='group', data=df, ax=axes[0])

# Box plot
sns.boxplot(x='group', y='x', data=df, ax=axes[1])

plt.tight_layout()
plt.show()

Seaborn allows you to easily create a variety of visually compelling plots, including scatter plots with hue and box plots.

5. Using plt.gridspec for Customized Grids

For intricate grid arrangements, plt.gridspec provides fine-grained control.

Example:

import matplotlib.pyplot as plt
import numpy as np

# Create a figure
fig = plt.figure(figsize=(8, 6))

# Define a grid layout
gs = fig.add_gridspec(nrows=3, ncols=3)

# Place plots in the grid
ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, :2])
ax3 = fig.add_subplot(gs[1:, 2])
ax4 = fig.add_subplot(gs[2, 0])
ax5 = fig.add_subplot(gs[2, 1])

# Plot data (replace with your actual data)
ax1.plot(np.arange(10), np.arange(10))
ax2.plot(np.arange(10), np.arange(10) ** 2)
ax3.plot(np.arange(10), np.arange(10) ** 3)
ax4.plot(np.arange(10), np.arange(10) ** 4)
ax5.plot(np.arange(10), np.arange(10) ** 5)

plt.tight_layout()
plt.show()

This example demonstrates how to create a customized grid and place individual plots within specific grid cells.

Conclusion

By utilizing these different methods, you can effectively display multiple plots in your Jupyter Notebook, enhancing your data analysis and visualization capabilities.

Featured Posts