Use tight_layout Colorbar and GridSpec in Matplotlib

I’ve come to appreciate the importance of creating clean, professional plots that communicate data effectively. Whether you’re visualizing economic trends across U.S. states or analyzing sales data, your plots need to be clear and well-organized. Two powerful tools in Matplotlib that help achieve this are tight_layout and GridSpec, especially when combined with colorbars.

In this article, I will share practical methods to use Matplotlib’s tight_layout, colorbar, and GridSpec features to create visually appealing and well-structured plots. I’ll walk you through multiple approaches, backed by real Python code examples, so you can apply these techniques to your own data visualization projects.

tight_layout in Python Matplotlib

When you create multiple subplots in Python using Matplotlib, you might notice overlapping labels, titles, or colorbars. This is where tight_layout() shines. It automatically adjusts subplot parameters to give enough padding between plots, making your visualizations cleaner.

Add Colorbars in Python Matplotlib: Two Effective Methods

Colorbars are essential when visualizing heatmaps or scatter plots with color mapping. However, placing colorbars correctly without disturbing the subplot layout can be tricky.

Method 1: Add Colorbar with fig.colorbar() Using Axes Reference

I prefer adding colorbars by explicitly passing the axis to fig.colorbar(). This method gives precise control over placement.

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 10)

fig, ax = plt.subplots(figsize=(6, 5))
cax = ax.imshow(data, cmap='viridis')
fig.colorbar(cax, ax=ax, orientation='vertical', fraction=0.046, pad=0.04)
plt.title('Random Heatmap')
plt.tight_layout()
plt.show()

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

tight_layout Colorbar in Matplotlib

Here, fraction controls the size of the colorbar relative to the axis, and pad adjusts the spacing between the plot and colorbar.

Method 2: Use make_axes_locatable for Colorbar Placement

For more complex layouts, I use make_axes_locatable from mpl_toolkits.axes_grid1 to add a colorbar axis next to the plot.

from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 10)

fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(data, cmap='plasma')

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
fig.colorbar(im, cax=cax, orientation='vertical')

plt.title('Random Heatmap with Divider Colorbar')
plt.tight_layout()
plt.show()

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

Use tight_layout Colorbar in Matplotlib

This method gives me full control over the colorbar size and position without affecting the main plot.

GridSpec in Python Matplotlib for Advanced Layouts

When you need non-uniform subplot sizes or complex layouts, GridSpec becomes invaluable. It allows you to create grids of subplots with varying row and column spans.

Method 1: Basic GridSpec Layout

I start by defining a grid with GridSpec and then assign subplots to specific grid cells.

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

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(3, 3)

ax1 = fig.add_subplot(gs[0, :])  # top row, all columns
ax2 = fig.add_subplot(gs[1, :-1])  # middle row, first two columns
ax3 = fig.add_subplot(gs[1:, -1])  # last column, last two rows
ax4 = fig.add_subplot(gs[-1, 0])  # bottom left corner
ax5 = fig.add_subplot(gs[-1, -2])  # bottom row, middle column

ax1.plot(x, y)
ax1.set_title('Top Row')

ax2.plot(x, np.cos(x))
ax2.set_title('Middle Left')

ax3.plot(x, np.tan(x))
ax3.set_title('Right Column')

ax4.plot(x, np.log1p(x))
ax4.set_title('Bottom Left')

ax5.plot(x, np.sqrt(x))
ax5.set_title('Bottom Middle')

plt.tight_layout()
plt.show()

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

tight_layout GridSpec in Matplotlib

This approach lets me customize subplot sizes and positions freely.

Method 2: Combine GridSpec with Colorbars

When using GridSpec, adding colorbars requires careful placement. I create dedicated grid cells for colorbars.

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

data1 = np.random.rand(10, 10)
data2 = np.random.rand(10, 10)

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

ax1 = fig.add_subplot(gs[0, 0])
im1 = ax1.imshow(data1, cmap='coolwarm')
ax1.set_title('Data 1')

ax2 = fig.add_subplot(gs[1, 0])
im2 = ax2.imshow(data2, cmap='viridis')
ax2.set_title('Data 2')

# Colorbars in dedicated column
cax1 = fig.add_subplot(gs[0, 2])
fig.colorbar(im1, cax=cax1)

cax2 = fig.add_subplot(gs[1, 2])
fig.colorbar(im2, cax=cax2)

plt.tight_layout()
plt.show()

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

Use tight_layout GridSpec in Matplotlib

By assigning the last column for colorbars, I maintain alignment and neat spacing.

Creating professional plots in Python with Matplotlib is all about mastering layout control. Using tight_layout() helps quickly fix spacing issues, while dedicated methods for colorbars ensure your legends don’t clutter the plot. For more complex arrangements, GridSpec offers unmatched flexibility.

Over the years, I’ve found that combining these tools allows me to build visualizations tailored for any dataset, from U.S. economic indicators to regional weather patterns, all with clean, readable layouts.

Try these methods in your next Python plotting project, and you’ll see how much easier it is to communicate your data clearly and professionally.

Related Python Matplotlib articles you may also like:

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.