Bor*_*lik 16 python plot matplotlib
在maptplotlib中,可以使用imshow函数创建相关矩阵的热图表示.根据定义,这种矩阵围绕其主对角线对称,因此不需要呈现上三角和下三角.例如:

上面的例子来自这个网站 不幸的是,我无法弄清楚如何在matplotlib中做到这一点.将矩阵的上/下部分设置为无会导致黑色三角形.我用google搜索"matplotlib缺失值",但找不到任何有用的东西
Bor*_*lik 22
doug提供的答案的问题在于它依赖于色图将零值映射到白色的事实.这意味着不包含白色的色彩图无效.解决方案的关键是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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
情节http://img444.imageshack.us/img444/9585/cmapgrayr.png
我得到的最好的答案是来自 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)
Run Code Online (Sandbox Code Playgroud)