在maptplotlib中,可以使用imshow函数创建相关矩阵的热图表示。根据定义,这种矩阵围绕其主对角线对称,因此不需要呈现上三角和下三角。例如:
以上示例取自this site 不幸的是,我无法弄清楚如何在matplotlib中做到这一点。将矩阵的上/下部分设置为无会导致黑色三角形。我用google搜索“matplotlib缺失值”,但找不到任何有用的信息
答案 0 :(得分:19)
doug提供的答案问题在于它依赖于色图将零值映射为白色的事实。这意味着不包含白色的色彩图无效。解决方案的关键是cm.set_bad
功能。使用None或使用NumPy蒙版数组和set_bad
将白色的不需要部分掩盖为白色,而不是默认的黑色。采用道格的例子,我们得到以下结论:
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 :(得分: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()
答案 2 :(得分:2)
您可以绘制一个白色矩阵,上/下部分透明
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')
答案 3 :(得分:1)
使用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
在线文档进行化妆。
答案 4 :(得分:0)
我得到的最佳答案是来自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)