代码之家  ›  专栏  ›  技术社区  ›  Boris Gorelik

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

  •  16
  • Boris Gorelik  · 技术社区  · 15 年前

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

    以上示例摘自 this site 不幸的是,我不知道如何在Matplotlib中实现这一点。将矩阵的上/下半部分设置为“无”将导致黑色三角形。我在谷歌上搜索了“Matplotlib缺少值”,但找不到任何有用的信息使用imshow功能。根据定义,这样的矩阵围绕其主对角线对称,因此不需要同时显示上下三角形。例如: correlation matrix

    上面的例子取自 this site 不幸的是,我不知道如何在Matplotlib中实现这一点。将矩阵的上/下半部分设置为“无”将导致黑色三角形。我在google上搜索了“matplotlib缺少值”,但找不到任何有用的信息。

    4 回复  |  直到 6 年前
        1
  •  18
  •   Boris Gorelik    15 年前

    Doug提供的答案的问题在于它依赖于这样一个事实:颜色映射将零值映射为白色。这意味着不包括白色的颜色映射是不有用的。解决的关键是 cm.set_bad 功能。您可以用无或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()
    
        2
  •  7
  •   doug    15 年前
    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
  •  2
  •   remosu    15 年前

    可以在一个白色矩阵上绘制上部/下部透明的图。

    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

        4
  •  0
  •   jhurst5    6 年前

    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)
    

    请参阅 西伯恩 联机文档进行补充。

    推荐文章