Plotting only upper/lower triangle of a heatmap

匿名 (未验证) 提交于 2019-12-03 01:14:02

问题:

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:

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

回答1:

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


回答2:

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 http://img444.imageshack.us/img444/9585/cmapgrayr.png



回答3:

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

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



回答4:

With seaborn and numpy, a quick solution is:

import matplotlib.pyplot as plt import seabon 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 seaborn online document for makeup.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!