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()
pcolormesh
,这正是我需要的解决方案。另外请注意,在代码行mask=NP.tri(A.shape[0],k=0)
中,将k=-1
更改为k=0
以排除对角线。 - VloxA = NP.ma.array(A, mask=mask).T
后添加 .T
即可。 - Vloxcmap.set_bad()
这一步,因为它们已经将其设置为白色。你可以通过打印cmap.get_bad()
来验证。你应该会得到array([0., 0., 0., 0.])
。 - LeviAckerman我得到的最佳答案来自seaborn。输出是一个光滑且外观简单的图形。这个函数将三角形保存到本地。
def get_lower_tri_heatmap(df, output="cooc_matrix.png"):
mask = np.zeros_like(df, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Want diagonal elements as well
mask[np.diag_indices_from(mask)] = False
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns_plot = sns.heatmap(data, mask=mask, cmap=cmap, vmax=.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
# save to file
fig = sns_plot.get_figure()
fig.savefig(output)
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()
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')
热图的上/下三角区域 http://lh5.ggpht.com/_ZgVr3-a-Z00/S4P3_BWByKI/AAAAAAAAAXE/UsJpokz6LKE/pp.png
seaborn
、matplotlib
和 numpy
,快速解决方案如下: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)
seaborn
的在线文档进行美化。xticklabels=corr.columns.values
选项。解决方法是首先声明名称(例如xnames=corr.columns.values
),然后使用np.triu()
,最后将xticklabels=xnames
作为参数发送。 - Mitchell van Zuylenyou can use this code:
from string import ascii_letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 26)),
columns=list(ascii_letters[26:]))
# Compute the correlation matrix
corr = d.corr()
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})