Home > Backend Development > Python Tutorial > How to Create Subplots with Different Sizes in Matplotlib?

How to Create Subplots with Different Sizes in Matplotlib?

Patricia Arquette
Release: 2024-11-30 08:23:13
Original
954 people have browsed it

How to Create Subplots with Different Sizes in Matplotlib?

Customizing the Size of Subplots

In Matplotlib, creating subplots with differing sizes can be achieved using various methods. To create a wider subplot, you can utilize the 'fig' function.

Using 'fig' with 'subplots'

To adjust the first subplot's size, modify the 'figsize' argument in the constructor. However, changing the second plot's size requires a different approach.

import matplotlib.pyplot as plt

# Create a figure and subplots with different width ratios
f, (a0, a1) = plt.subplots(1, 2, width_ratios=[3, 1])

# Add plots to the subplots
a0.plot(data_1)  # Plot data to the first subplot (wider)
a1.plot(data_2)  # Plot data to the second subplot

# Save the figure to PDF
f.savefig('grid_figure.pdf')
Copy after login

Using 'subplots' and 'gridspec_kw'

Alternatively, you can use the 'subplots' function and pass the width ratio argument with 'gridspec_kw'.

import numpy as np
import matplotlib.pyplot as plt

# Generate data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# Plot using subplots with gridspec_kw
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})

# Add plots to the subplots
a0.plot(x, y)
a1.plot(y, x)

# Save the figure to PDF
f.tight_layout()
f.savefig('grid_figure.pdf')
Copy after login

Vertical Subplots

To create subplots with different heights, modify the 'height_ratios' argument in 'gridspec_kw'.

# Create a figure and subplots with different height ratios
f, (a0, a1, a2) = plt.subplots(3, 1, gridspec_kw={'height_ratios': [1, 1, 3]})

# Add plots to the subplots
a0.plot(x, y)
a1.plot(x, y)
a2.plot(x, y)

# Save the figure to PDF
f.tight_layout()
f.savefig('grid_figure.pdf')
Copy after login

The above is the detailed content of How to Create Subplots with Different Sizes in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template