仅绘制热图的上/下三角形 [英] Plotting only upper/lower triangle of a heatmap

查看:468
本文介绍了仅绘制热图的上/下三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

以上示例取自本网站 不幸的是,我不知道如何在matplotlib中执行此操作.将矩阵的上/下部分设置为无"会产生黑色三角形.我在Google上搜索了"matplotlib缺少值",但找不到任何有用的方法

The above example was taken from this site Unfortunately, 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

推荐答案

doug提供的答案的问题在于,它依赖于色图将零值映射到白色这一事实.这意味着不包含白色的颜色图将无用.解决方案的关键是cm.set_bad功能.您可以使用None或使用NumPy掩码的数组,将set_bad屏蔽为矩阵的不需要部分,将其屏蔽为白色,而不是默认的黑色.以道格为例,我们得到以下信息:

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_bad function. You mask the unneeded parts of the matrix with None or with NumPy masked arrays and set_bad to white, instead of the default black. Adopting doug's example we get the following:

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

这篇关于仅绘制热图的上/下三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆