Plotting two distance matrices together on same plot?

后端 未结 1 1133
情歌与酒
情歌与酒 2020-12-04 00:29

I\'m trying to create dendrograms from two different distance matrices and compare them. I used the code here as a starting point, but the problem is since I\'m using two di

相关标签:
1条回答
  • 2020-12-04 00:39

    There is no built-in method to draw an image consisting of triangles, cutting the pixels in half.

    So one would need to build some custom heatmap. This could be done using a PolyCollection of triangles. In the solution below a function creates the points of a triangle around the origin, rotates them if needed, and applies an offset. Looping over the array allows to create a triangle for each point. Finally all those triangles are collected into a PolyCollection.

    You may then decide to use a normal imshow or matshow plot for one of the arrays and the custom triangle matrix on top of it.

    import matplotlib.pyplot as plt
    import matplotlib.collections as collections
    import numpy as np
    
    def triatpos(pos=(0,0), rot=0):
        r = np.array([[-1,-1],[1,-1],[1,1],[-1,-1]])*.5
        rm = [[np.cos(np.deg2rad(rot)), -np.sin(np.deg2rad(rot))],
               [np.sin(np.deg2rad(rot)),np.cos(np.deg2rad(rot)) ] ]
        r = np.dot(rm, r.T).T
        r[:,0] += pos[0]
        r[:,1] += pos[1]
        return r
    
    def triamatrix(a, ax, rot=0, cmap=plt.cm.viridis, **kwargs):
        segs = []
        for i in range(a.shape[0]):
            for j in range(a.shape[1]):
                segs.append(triatpos((j,i), rot=rot) )
        col = collections.PolyCollection(segs, cmap=cmap, **kwargs)
        col.set_array(a.flatten())
        ax.add_collection(col)
        return col
    
    
    A,B = np.meshgrid(range(5), range(4))
    B*=4
    
    fig, ax=plt.subplots()
    im1 = ax.imshow(A)
    im2 = triamatrix(B, ax, rot=90, cmap="Reds")
    
    fig.colorbar(im1, ax=ax, )
    fig.colorbar(im2, ax=ax, )
    
    plt.show()
    

    Triangle heatmap

    Of course it would be equally possible to use two of those triangle matrices

    im1 = triamatrix(A, ax, rot=0, cmap="Blues")
    im2 = triamatrix(B, ax, rot=180, cmap="Reds")
    ax.set_xlim(-.5,A.shape[1]-.5)
    ax.set_ylim(-.5,A.shape[0]-.5)
    

    which would also require to set the axis limits manually.

    0 讨论(0)
提交回复
热议问题