Customize Matplotlib Subplots with Gridspec and Grid Color

I first started working with Matplotlib in Python, and I often struggled with subplot layouts. Sometimes my charts would overlap, or the spacing just didn’t look professional.

After more than 10 years of experience as a Python developer, I’ve realized that two powerful tools can completely change the way you design subplots: Gridspec and grid color customization.

In this tutorial, I will walk you through both methods step by step. I’ll use real-world examples that you can easily apply to your own Python projects. By the end, you’ll be able to create subplots that not only look clean but also communicate your data more effectively.

Customize Subplots Using Gridspec in Python

When you need more control over subplot layouts than plt.subplot() or plt.subplots(), the Gridspec class is the best solution. It allows you to define flexible grids and decide how much space each subplot should take.

I often use this when I need one large plot and a few smaller ones side by side. Let me show you how to do this in Python.

Method 1 – Create a Basic Gridspec Layout

The first method is to create a simple Gridspec layout with different subplot sizes.

Here’s the Python code:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

# Sample data for USA monthly sales (in million USD)
months = np.arange(1, 13)
sales = np.random.randint(50, 200, size=12)
expenses = np.random.randint(30, 150, size=12)

# Create a figure with Gridspec
fig = plt.figure(figsize=(10, 6))
gs = gridspec.GridSpec(2, 2, figure=fig)

# Large subplot for sales
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(months, sales, marker='o', color='blue', label="Sales")
ax1.set_title("Monthly Sales in the USA")
ax1.set_xlabel("Month")
ax1.set_ylabel("Sales (Million USD)")
ax1.legend()

# Bottom-left subplot for expenses
ax2 = fig.add_subplot(gs[1, 0])
ax2.bar(months, expenses, color='orange')
ax2.set_title("Monthly Expenses")

# Bottom-right subplot for profit
profit = sales - expenses
ax3 = fig.add_subplot(gs[1, 1])
ax3.plot(months, profit, marker='s', color='green', label="Profit")
ax3.set_title("Monthly Profit")
ax3.legend()

plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Customize Matplotlib Subplots with Gridspec, Grid Color

This code creates one large chart on top for sales and two smaller ones below for expenses and profit.

I use this layout often when presenting financial reports because it keeps the main chart in focus while still showing supporting information.

Method 2 – Customize Gridspec Column and Row Widths

The second method is to customize the width ratios and height ratios in Gridspec. This is helpful when one subplot needs more space than the others.

Here’s the Python code:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

# USA temperature data (Fahrenheit)
months = np.arange(1, 13)
new_york = np.random.randint(30, 90, size=12)
los_angeles = np.random.randint(50, 100, size=12)

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

# Larger subplot for New York
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(months, new_york, color='blue', label="New York")
ax1.set_title("New York Monthly Temperatures")
ax1.legend()

# Smaller subplot for Los Angeles
ax2 = fig.add_subplot(gs[0, 1])
ax2.plot(months, los_angeles, color='red', label="Los Angeles")
ax2.set_title("Los Angeles Temperatures")
ax2.legend()

# Wide subplot at the bottom for comparison
ax3 = fig.add_subplot(gs[1, :])
ax3.plot(months, new_york, color='blue', label="New York")
ax3.plot(months, los_angeles, color='red', label="Los Angeles")
ax3.set_title("Temperature Comparison")
ax3.legend()

plt.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

Matplotlib Subplots with Gridspec and Grid Color

This method gives you precise control over subplot sizes. I often use it when comparing datasets like city temperatures, where one chart needs more attention than others.

Customize Subplots with Grid Color in Python

Another way to make your subplots more readable is to customize the grid color. By default, Matplotlib uses light gray grid lines, but you can change their color, style, and transparency.

I’ve found that customizing grid colors is especially useful when presenting charts to clients. A well-chosen grid color makes the data easier to read without distracting from the main plot.

Method 1 – Change Grid Color for a Single Subplot

The first method is to change the grid color for a single subplot.

Here’s the Python code:

import matplotlib.pyplot as plt
import numpy as np

# USA unemployment rate data (%)
months = np.arange(1, 13)
unemployment = np.random.uniform(3.5, 8.0, size=12)

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(months, unemployment, marker='o', color='purple', label="Unemployment Rate")

# Customize grid
ax.grid(True, color='lightblue', linestyle='--', linewidth=0.7)
ax.set_title("Unemployment Rate in the USA")
ax.set_xlabel("Month")
ax.set_ylabel("Rate (%)")
ax.legend()

plt.show()

I executed the above example code and added the screenshot below.

Customize Subplots with Gridspec and Grid Color in Matplotlib

In this example, I changed the grid color to light blue with dashed lines. This makes the chart look cleaner and easier to read.

Method 2 – Apply Grid Color to Multiple Subplots

The second method is to apply grid color customization to multiple subplots at once.

Here’s the Python code:

import matplotlib.pyplot as plt
import numpy as np

# USA stock market index data
days = np.arange(1, 31)
dow_jones = np.random.randint(30000, 35000, size=30)
nasdaq = np.random.randint(12000, 14000, size=30)

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))

# Dow Jones subplot
ax1.plot(days, dow_jones, color='blue', label="Dow Jones")
ax1.set_title("Dow Jones Index")
ax1.grid(True, color='gray', linestyle=':', linewidth=0.8)
ax1.legend()

# Nasdaq subplot
ax2.plot(days, nasdaq, color='green', label="Nasdaq")
ax2.set_title("Nasdaq Index")
ax2.grid(True, color='orange', linestyle='--', linewidth=0.8)
ax2.legend()

plt.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

Subplots with Gridspec and Grid Color in Matplotlib

Here, I used different grid colors for each subplot. This makes it clear that each chart tells a separate story while still being part of the same figure.

Conclusion

Customizing subplots in Matplotlib with Gridspec and grid color has completely changed the way I present data in Python.

With Gridspec, I can design flexible layouts that highlight the most important charts. With grid color customization, I can make my plots more readable and visually appealing.

Both methods are easy to apply, and once you start using them, you’ll notice a big improvement in how professional your Python charts look.

You may also like to read other Matplotlib tutorials:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.