Euler_Salter
Euler_Salter

Reputation: 3561

Matplotlib - Tight layout of multiple subplots with colorbar

I have a series of subplots in a single row, all sharing the same colorbar and I would like to use plt.tight_layout().

However when used naively, the colorbar messes everything up. Luckily, I found this in the matplotlib documentation, but it works only for one subplot.

Minimal Working Example

I tried to adapt it to multiple subplots but the subplot to which the colorbar is assigned to ends up being smaller.

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

plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig, ax = plt.subplots(ncols=2, figsize=(8, 4))
im0 = ax[0].imshow(arr, interpolation="none")
im1 = ax[1].imshow(arr, interpolation='none')

divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im0, cax=cax)

plt.tight_layout()

This is what the result looks like.

enter image description here

Upvotes: 1

Views: 3761

Answers (1)

Jody Klymak
Jody Klymak

Reputation: 5913

With the newest matplotlib (3.6), there is a new option layout='compressed' for this situation:

import matplotlib.pyplot as plt
import numpy as np

arr = np.arange(100).reshape((10, 10))
fig, ax = plt.subplots(ncols=2, figsize=(4, 2), layout='compressed')
im0 = ax[0].imshow(arr)
im1 = ax[1].imshow(arr)

plt.colorbar(im0, ax=ax)
plt.show()

enter image description here

Upvotes: 7

Related Questions