2014-07-17 38 views

回答

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

enter image description here

这个问题是你需要照顾泰德val是不是在数组中。您可以为此添加一个简单的检查,或将其基于您正在使用的数据。 for循环可能是矢量化的,但我无法弄清楚。