12221 观看

4回复

11290 作者的声誉

### 回应 4

7

53590 作者的声誉

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

2

3627 作者的声誉

``````a =random((10,10))
imshow(a, interpolation='nearest')

b = ones(a.shape+(4,)) # «white» matrix with alpha=1
for i in range(a.shape[0]):
for j in range(i, a.shape[1]):
b[i,j,3] = 0   # upper triangle, alpha = 0
imshow(b, interpolation='nearest')
``````

18

11290 作者的声誉

doug提供的答案的问题在于它依赖于色图将零值映射到白色的事实。这意味着不包含白色的色彩图无效。解决方案的关键是`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()
``````

1

2062 作者的声誉

``````import matplotlib.pyplot as plt
import seaborn 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)
``````