Python matplotlib色条:全部位于最后一个轴上

2024-06-06 22:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我的所有色条都显示在最后一个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()

我做错了什么?如何解决?你知道吗


Tags: import密码numbermatplotlibasnpfigplt
1条回答
网友
1楼 · 发布于 2024-06-06 22:22:55

您需要将axis实例作为参数传递给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

相关问题 更多 >