Python Matplotlib颜色条:全部位于最后一个轴

时间:2018-09-15 10:09:02

标签: python matplotlib colorbar

我所有的颜色条都出现在最后一个imshow()轴上

All scalebars stuck to the bottom-most image

这是我的代码:

"""
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()

我在做什么错以及如何解决?

1 个答案:

答案 0 :(得分:2)

您需要将轴实例作为参数传递给colorbar,如下所示。我已经通过注释突出显示了修改后的行。其余代码保持不变

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()

输出

enter image description here