Python matplotlib colorbars:全部在最后一个轴上

问题描述 投票:2回答:1

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

这是我的代码:

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

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

python matplotlib colorbar
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.