Search code examples
pythonmatplotlibcolorbar

Python matplotlib colorbars: all on last axis


All of my colorbars appear on the last imshow() axis:

All scalebars stuck to the bottom-most image

Here is my code:

"""
Least replicable unit
"""
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
number = 3
Images = np.random.rand(400, number)
Spectra = np.random.rand(100, number)

fig, cax = plt.subplots(nrows=number, ncols=2)
for i in range(number):
    cax[i, 0].plot(Spectra[:, i])
    P = cax[i, 1].imshow(Images[:,i].reshape((20, 20)))
    fig.colorbar(P)
    plt.tight_layout()

What am I doing wrong and how to fix it?


Solution

  • You need to pass the axis instance to the colorbar as an argument as follows. I have highlighted the modified line by a comment. Rest of the code remains the same

    for i in range(number):
        cax[i, 0].plot(Spectra[:, i])
        P = cax[i, 1].imshow(Images[:,i].reshape((20, 20)))
        fig.colorbar(P, ax=cax[i, 1]) # Modified here
        plt.tight_layout()
    

    Output

    enter image description here