2010-02-23 197 views
14

在maptplotlib中,可以使用imshow函數創建相關矩陣的熱圖表示。根據定義,這樣的矩陣是圍繞其主對角線對稱的,因此不需要同時呈現上下三角形。例如: correlation matrix僅繪製熱圖上/下三角形

上面的例子是從this site 不幸的是採取了,我無法弄清楚如何在matplotlib做到這一點。將矩陣的上/下部分設置爲None將導致黑色三角形。我用Google搜索了「matplotlib遺漏值」,但找不到任何有用的

+1

也許他們只是photoshopped它:) – endolith 2011-05-14 22:46:09

回答

16

道格提供的答案的問題是它依賴於色彩貼圖將零值映射到白色的事實。這意味着不包含白色的顏色映射無用。解決問題的關鍵是cm.set_bad函數。你用None或用NumPy蒙版陣列和set_bad將不需要的部分掩蓋爲白色,而不是默認的黑色。採用Doug的例子中,我們得到如下:

import numpy as NP 
from matplotlib import pyplot as PLT 
from matplotlib import cm as CM 

A = NP.random.randint(10, 100, 100).reshape(10, 10) 
mask = NP.tri(A.shape[0], k=-1) 
A = NP.ma.array(A, mask=mask) # mask out the lower triangle 
fig = PLT.figure() 
ax1 = fig.add_subplot(111) 
cmap = CM.get_cmap('jet', 10) # jet doesn't have white color 
cmap.set_bad('w') # default value is 'k' 
ax1.imshow(A, interpolation="nearest", cmap=cmap) 
ax1.grid(True) 
PLT.show() 
+0

不錯!與'pcolormesh'一起工作,這正是我需要的解決方案。還要注意排除對角線,並在'mask = NP.tri(A.shape [0],k = 0)行中將'k = -1'更改爲'k = 0' – Vlox 2017-05-10 15:12:16

7
import numpy as NP 
from matplotlib import pyplot as PLT 
from matplotlib import cm as CM 

A = NP.random.randint(10, 100, 100).reshape(10, 10) 
# create an upper triangular 'matrix' from A 
A2 = NP.triu(A) 
fig = PLT.figure() 
ax1 = fig.add_subplot(111) 
# use dir(matplotlib.cm) to get a list of the installed colormaps 
# the "_r" means "reversed" and accounts for why zero values are plotted as white 
cmap = CM.get_cmap('gray_r', 10) 
ax1.imshow(A2, interpolation="nearest", cmap=cmap) 
ax1.grid(True) 
PLT.show() 

plot http://img444.imageshack.us/img444/9585/cmapgrayr.png

+1

謝謝你包括你的進口。可運行的示例非常有用。 – jcdyer 2010-02-23 16:06:45

0

隨着seabornnumpy,一個快速的解決方案是:

import matplotlib.pyplot as plt 
import seabon as sns 

# Say your matrix object (e.g. np.array) is corr_mat 

# Get the upper triangle without the diagonal 
corr_mat = np.triu(corr_mat, k=1) 

# Plot the heatmap 
ax = sns.heatmap(corr_mat) 

請參閱seaborn在線文檔化妝。