python - 在同一个图上一起绘制两个距离矩阵?

标签 python matrix matplotlib scipy

我正在尝试从两个不同的距离矩阵创建树状图并进行比较。我使用了代码 here作为起点,但问题是因为我使用的是两个不同的矩阵但聚类方法相同,所以我需要将两个不同的矩阵绘制在一起以进行比较分析。我想知道是否可以将每个正方形/节点对角线分成两半以显示两个不同的距离矩阵。

这张图片代表了我的目标结果: enter image description here

这是我的代码:

from sklearn import preprocessing
from sklearn.neighbors import DistanceMetric 
import pandas as pd
import numpy as np
from ete3 import Tree
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import cosine_distances
import scipy
import pylab
import scipy.cluster.hierarchy as sch
import scipy.spatial.distance as sd 
import random
#g[n] is a one dimensional array containing datapoints
g1 = random.sample(range(30), 5)
g2 = random.sample(range(30), 5)
g3 = random.sample(range(30), 5)
g4 = random.sample(range(30), 5)
g5 = random.sample(range(30), 5)
g1 = np.array(g1)
g2 = np.array(g2)
g3 = np.array(g3)
g4 = np.array(g4)
g5 = np.array(g5)
X = (g1,g2,g3,g4,g5)
#Comparing between euclidean and cosine###########################################
distanceC = cosine_distances(X)
dist = DistanceMetric.get_metric('euclidean')
distanceE = dist.pairwise(X)
##################################################################################

#Plots############################################################################

# Compute and plot first dendrogram.
fig = pylab.figure(figsize=(8,8))
ax1 = fig.add_axes([0.09,0.1,0.2,0.6])
Y = sch.average(sd.squareform(distanceC))
Z1 = sch.dendrogram(Y, orientation='right')
ax1.set_xticks([])
ax1.set_yticks([])

# Compute and plot second dendrogram.
ax2 = fig.add_axes([0.3,0.71,0.6,0.2])
Y = sch.average(sd.squareform(distanceE))
Z2 = sch.dendrogram(Y)
ax2.set_xticks([])
ax2.set_yticks([])

# Plot distance matrix.
axmatrix = fig.add_axes([0.3,0.1,0.6,0.6])
idx1 = Z1['leaves']
idx2 = Z2['leaves']
distance = distance[idx1,:]
distance = distance[:,idx2]
im = axmatrix.matshow(distance, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu)
axmatrix.set_xticks([])
axmatrix.set_yticks([])

# Plot colorbar.
axcolor = fig.add_axes([0.91,0.1,0.02,0.6])
pylab.colorbar(im, cax=axcolor)
fig.show()
fig.savefig('dendrogram.png')
##################################################################################

最佳答案

没有内置方法来绘制由三角形组成的图像,将像素切成两半。

因此需要构建一些自定义热图。这可以使用三角形的 PolyCollection 来完成。在下面的解决方案中,一个函数围绕原点创建三角形的点,根据需要旋转它们,并应用偏移量。遍历数组允许为每个点创建一个三角形。最后,所有这些三角形都被收集到一个 PolyCollection 中。

然后您可以决定对其中一个数组使用普通的 imshowmatshow 绘图,并在其顶部使用自定义三角矩阵。

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

当然也可以使用其中两个三角形矩阵

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)

这还需要手动设置轴限制。

关于python - 在同一个图上一起绘制两个距离矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44291155/

相关文章:

python - 试图在谷歌云中查找已部署的 python 函数的当前项目 ID 会出错

python - Python 中矩阵值的数值积分

python - 无法使用 ipython 笔记本内联绘图

python - 对 matplotlib 颜色的颜色代码感到好奇

python - 在python类中创建pybullet客户端的多个实例

python - 使用字典值更新查询集

python - 创建可用值的分布 - Python

python - 注释不会出现在 matplotlib 图中

python - 查找与另一个大列表重叠/相交的大列表的子集

c++ - 使用 openCV 创建 super 矩阵