2
有沒有辦法使用matplotlib繪製不同行長度的熱圖?python matplotlib imshow與數據數組中的不同長度
這樣的:
plt.imshow([ [1,2,3], [1,2], [1,2,3,4,5,6,7], [1,2,3,4]])
plt.jet()
plt.colorbar()
plt.show()
有沒有辦法使用matplotlib繪製不同行長度的熱圖?python matplotlib imshow與數據數組中的不同長度
這樣的:
plt.imshow([ [1,2,3], [1,2], [1,2,3,4,5,6,7], [1,2,3,4]])
plt.jet()
plt.colorbar()
plt.show()
鑑於所需的圖像,我想你會想你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循環可能是矢量化的,但我無法弄清楚。
爲每一行使用一個單獨的「ishow」。使用「範圍」kwarg來平鋪它們 – tacaswell