How to create different subplot sizes in Matplotlib?
×


How to create different subplot sizes in Matplotlib?

588

How to Create Subplots with Different Sizes in Matplotlib

When visualizing data, sometimes you want your subplots to have different sizes to highlight specific charts or to better fit your data. Matplotlib offers flexible tools to customize subplot sizes within a single figure. Let’s explore how you can achieve this.

Using GridSpec to Control Subplot Sizes

The GridSpec module from Matplotlib lets you create complex subplot layouts by defining grid rows and columns with customizable size ratios. You can specify the relative width and height for each subplot, allowing for varied subplot sizes.

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

fig = plt.figure(figsize=(8, 6))
gs = GridSpec(2, 2, width_ratios=[3, 1], height_ratios=[1, 2])

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, :])

ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_title('Large Width Plot')

ax2.scatter([1, 2, 3], [1, 4, 9])
ax2.set_title('Smaller Width Plot')

ax3.bar([1, 2, 3], [1, 4, 9])
ax3.set_title('Wide Bottom Plot')

plt.tight_layout()
plt.show()

In this example, the first row has two subplots with widths in a 3:1 ratio, while the bottom subplot spans both columns with a height twice the size of the first row.

Using gridspec_kw in plt.subplots() for Quick Layouts

For simpler cases, you can use the gridspec_kw argument inside plt.subplots() to specify size ratios without manually creating a GridSpec object.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 2, figsize=(8, 4), gridspec_kw={'width_ratios': [2, 1]})

axs[0].plot([1, 2, 3], [1, 4, 9])
axs[0].set_title('Wider Subplot')

axs[1].scatter([1, 2, 3], [1, 4, 9])
axs[1].set_title('Narrower Subplot')

plt.tight_layout()
plt.show()

This method quickly creates two subplots side by side where the first one is twice as wide as the second.

Combining Different Plot Types with Varying Sizes

You can combine different plot types (line, scatter, bar, pie, etc.) within a figure, assigning each a custom size to suit your needs. This helps in creating dashboards or reports where some plots need to stand out.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(12, 8))
gs = fig.add_gridspec(3, 3)

# Large line plot spanning two columns
ax1 = fig.add_subplot(gs[0, :2])
x = np.linspace(0, 10, 100)
ax1.plot(x, np.sin(x), label='Sine Wave')
ax1.plot(x, np.cos(x), label='Cosine Wave')
ax1.set_title('Line Plot')
ax1.legend()

# Small scatter plot
ax2 = fig.add_subplot(gs[0, 2])
n = 30
ax2.scatter(np.random.rand(n), np.random.rand(n), c=np.random.rand(n), s=50)
ax2.set_title('Scatter Plot')

# Bar plot spanning the entire second row
ax3 = fig.add_subplot(gs[1, :])
categories = ['A', 'B', 'C', 'D']
values = [4, 7, 1, 8]
ax3.bar(categories, values)
ax3.set_title('Bar Plot')

# Pie chart in bottom left corner
ax4 = fig.add_subplot(gs[2, 0])
sizes = [20, 30, 25, 25]
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
ax4.pie(sizes, labels=labels, autopct='%1.1f%%')
ax4.set_title('Pie Chart')

# Heatmap taking bottom right two columns
ax5 = fig.add_subplot(gs[2, 1:])
data = np.random.rand(10, 10)
im = ax5.imshow(data, cmap='viridis')
ax5.set_title('Heatmap')
fig.colorbar(im, ax=ax5, fraction=0.046, pad=0.04)

plt.tight_layout()
plt.show()

This layout balances multiple plot types and sizes to deliver a clear, organized visualization.

Summary

Matplotlib’s GridSpec and gridspec_kw provide powerful ways to create subplots with different sizes within the same figure. This flexibility enables you to design visually appealing and well-organized data presentations, highlighting important plots as needed.


If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat