2014-07-17 37 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循環可能是矢量化的,但我無法弄清楚。