Positioning Multiple Colorbars outside of Subplots (matplotlib)

Viewed 143

I have a figure with multiple subplot rows that all share an x axis. Some of the rows require a color bar, but the other rows don't. If I just use the color bar function, the subplots will be misaligned. How do I place the color bars outside of the subplots such that all the rows will still be aligned?

figure with misaligned subplots

1 Answers

I made a function that may help:

import numpy as np
from matplotlib import pyplot as plt

#function to add colorbar for imshow data and axis
def add_colorbar_outside(im,ax):
    fig = ax.get_figure()
    bbox = ax.get_position() #bbox contains the [x0 (left), y0 (bottom), x1 (right), y1 (top)] of the axis.
    width = 0.01
    eps = 0.01 #margin between plot and colorbar
    # [left most position, bottom position, width, height] of color bar.
    cax = fig.add_axes([bbox.x1 + eps, bbox.y0, width, bbox.height])
    cbar = fig.colorbar(im, cax=cax)

#Example code:
x = np.random.random((10, 100))
fig, axes = plt.subplots(5,1, sharex = True)
im = axes[0].imshow(x, cmap = "Reds", aspect="auto", origin="lower")
add_colorbar_outside(im, axes[0])
im2 = axes[2].imshow(x, cmap = "coolwarm", aspect="auto", origin="lower")
add_colorbar_outside(im2, axes[2])
plt.show()

figure with colorbars outside

Related