Python Matplotlib imshow 处理不同长度的数据数组

2 投票
1 回答
730 浏览
提问于 2025-04-18 13:41

有没有办法用matplotlib画出行长度不一样的热力图呢?

像这样:

plt.imshow( [ [1,2,3], [1,2], [1,2,3,4,5,6,7], [1,2,3,4]])
plt.jet()
plt.colorbar()
plt.show()

想要的图片

1 个回答

2

根据你想要的图像,我觉得你可能更想用 plt.pcolormesh 而不是 imshow,不过我也可能猜错了。无论如何,我个人会先写一个函数来给数组加边框,然后再用一个遮罩,这样 imshowpcolormesh 就不会把那些点画出来。比如说:

import matplotlib.pylab as plt
import numpy as np

def regularise_array(arr, val=-1):
    """ Takes irregular array and returns regularised masked array

    This first pads the irregular awway *arr* with values *val* to make 
    it of rectangular. It then applies a mask so that the padded values
    are not displayed by pcolormesh. For this reason val should not
    be in *arr* as you will loose these points.
    """

    lengths = [len(d) for d in data]
    max_length = max(lengths)
    reg_array = np.zeros(shape=(arr.size, max_length))

    for i in np.arange(arr.size):
        reg_array[i] = np.append(arr[i], np.zeros(max_length-lengths[i])+val)

    reg_array = np.ma.masked_array(reg_array, reg_array == val)

    return reg_array

data = np.array([[1,2,3], [1,2], [1,2,3,4,5,6,7], [1,2,3,4]])

reg_data = regularise_array(data, val=-1)

plt.pcolormesh(reg_data)
plt.jet()
plt.colorbar()
plt.show()

在这里输入图片描述

这里的问题是你需要确保 val 不在数组里。你可以简单检查一下,或者根据你使用的数据来决定。那个 for 循环可能可以优化成向量化的形式,但我现在还不知道怎么做。

撰写回答