2010-02-23 24 views
14

In maptplotlib kann mit der Funktion imshow eine Heatmap-Darstellung einer Korrelationsmatrix erstellt werden. Per Definition ist eine solche Matrix symmetrisch um ihre Hauptdiagonale herum, daher ist es nicht notwendig, sowohl das obere als auch das untere Dreieck zu präsentieren. Zum Beispiel: correlation matrixPlotten nur des oberen/unteren Dreiecks einer Heatmap

Das obige Beispiel von this site Leider genommen wurde, kann ich nicht herausfinden, wie dies in matplotlib zu tun. Wird der obere/untere Teil der Matrix auf None gesetzt, entsteht ein schwarzes Dreieck. Ich habe gegoogelt "matplotlib Werte fehlen", konnte aber nichts hilfreich

+1

Vielleicht haben sie nur photoshopped :) – endolith

Antwort

16

Das Problem mit der Antwort von doug ist, dass es auf der Tatsache beruht, dass die Colormap null Werte auf weiß abbildet. Dies bedeutet, dass Colormaps, die keine weiße Farbe enthalten, nicht nützlich sind. Der Schlüssel zur Lösung ist cm.set_bad Funktion. Sie maskieren die nicht benötigten Teile der Matrix mit None oder mit NumPy maskierten Arrays und set_bad zu Weiß, anstelle des Standard-Schwarz. Dougs Beispiel Annahme erhalten wir folgende Möglichkeiten:

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

schön! arbeitet auch mit 'pcolormesh', für das ich diese Lösung brauchte. Beachten Sie auch, dass Sie die Diagonale ebenfalls ausschließen und in der Zeile 'mask = NP.tri (Ashape [0], k = 0)' 'k = -1' zu' k = 0' ändern – Vlox

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

Vielen Dank für Ihre Importe. Ausführbare Beispiele sind sehr hilfreich. – jcdyer

0

Mit seaborn und numpy, eine schnelle Lösung ist:

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) 

Benutzen Sie seaborn Online-Dokument für Make-up.