0

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

Euler_Salter
  • 3,271
  • 8
  • 33
  • 74
  • Can you please share what you wish to achieve by using `plt.tight_layout`? – medium-dimensional Oct 31 '22 at 18:55
  • 1
    @medium-dimensional good question. Basically I want the overall figure to have tight subplots meaning that the horizontal and vertical spaces are reduced. But I would like this to happen even if there's a colorbar: the horizontal space between all subplots and the colorbar is the same. However, I am also happy if the horizontal space between the right most subplot and the colorbar is smaller than that between plots, as long as all plots stay at the same size – Euler_Salter Oct 31 '22 at 19:03
  • 1
    To summarize: 1) all subplots to have the same size (vertical and horizontal) 2) colorbar to have same height as plots 3) being able to control spacing between plots – Euler_Salter Oct 31 '22 at 19:11
  • 1
    Please check this: https://stackoverflow.com/a/38940369/7789963 – medium-dimensional Oct 31 '22 at 19:37
  • 2
    And also this answer: https://stackoverflow.com/a/45634754/7789963 – medium-dimensional Oct 31 '22 at 19:45

1 Answers1

2

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

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31