python 仅绘制热图的上/下三角形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2318529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:21:46  来源:igfitidea点击:

Plotting only upper/lower triangle of a heatmap

pythonmatplotlibplot

提问by Boris Gorelik

In maptplotlib, one can create a heatmap representation of a correlation matrix using the imshow function. By definition, such a matrix is symmetrical around its main diagonal, therefore there is no need to present both the upper and lower triangles. For example: correlation matrix

在 maptplotlib 中,可以使用 imshow 函数创建相关矩阵的热图表示。根据定义,这样的矩阵围绕其主对角线对称,因此无需同时显示上三角形和下三角形。例如: 相关矩阵

The above example was taken from this siteUnfortunately, I couldn't figure out how to do this in matplotlib. Setting upper/lower part of the matrix to None results in black triangle. I have googled for "matplotlib missing values", but couldn't find anything helpful

上面的例子取自这个站点不幸的是,我无法弄清楚如何在 matplotlib 中做到这一点。将矩阵的上/下部分设置为 None 会导致黑色三角形。我在谷歌上搜索了“matplotlib 缺失值”,但找不到任何有用的信息

回答by Boris Gorelik

The problem with the answer provided by doug is that it relies on the fact that the colormap maps zero values to white. This means that colormaps that do not include white color are not useful. The key for solution is cm.set_badfunction. You mask the unneeded parts of the matrix with None or with NumPy masked arrays and set_badto white, instead of the default black. Adopting doug's example we get the following:

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

回答by 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)
# 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

阴谋

回答by remosu

You could plot over one white matrix with upper/lower part transparent

您可以在一个白色矩阵上绘制上/下部分透明

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')

upper/lower triangle of a heatmap http://lh5.ggpht.com/_ZgVr3-a-Z00/S4P3_BWByKI/AAAAAAAAAXE/UsJpokz6LKE/pp.png

热图的上/下三角形 http://lh5.ggpht.com/_ZgVr3-a-Z00/S4P3_BWByKI/AAAAAAAAAXE/UsJpokz6LKE/pp.png

回答by Itachi

The best answer i got was from seaborn. The output is a smooth and simple looking figure. This function saves the triangle to local

我得到的最好的答案是来自 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)

Lower triangle

下三角

回答by tagoma

With seaborn, matplotliband numpy, a quick solution is:

使用seaborn,matplotlibnumpy,快速解决方案是:

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)

Please, refer to seabornonline document for makeup.

请参阅seaborn在线文档进行化妆。