Python matplotlib 颜色条 : all on last axis

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

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

最佳答案

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

关于Python matplotlib 颜色条 : all on last axis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343717/

相关文章:

python - 使用 Paramiko 在命令内传递 Python 变量

python - matplotlib 颜色条交替顶部底部标签

python - 男女通用浴室 : Threading in Python

python - aioredis + aiohttp 正确使用连接池

python - 使用python计算肽单同位素

python - 我可以从颜色列表和 for 循环中绘制颜色条吗?

python - 彩条/绘图问题? "posx and posy should be finite values"

python - Matplotlib imshow,基于缩放动态重采样

Python-KeyError : 'adm0_a3' when using cartopy

python - 使用 pyplot 返回复数值的绘图函数