Skip to main content
 首页 » 编程设计

python matplotlib imshow 在数据数组中具有不同的长度

2024年10月25日8linjiqin

有没有办法使用 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() 

Desired image

请您参考如下方法:

鉴于所需的图像,我想您会想要 plt.pcolormesh 而不是 imshow 但我可能错了。在任何情况下,我个人都会创建一个函数来填充数组,然后使用掩码,这样 imshow 或 pcolormesh 就不会绘制这些点。例如

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 循环可能是矢量化的,但我不知道如何进行。