matrix - 将距离矩阵可视化为图形

标签 matrix data-visualization

我正在做一个聚类任务,我有一个距离矩阵。我希望将此距离矩阵可视化为二维图。请让我知道是否有任何方法可以在线或使用 R 或 python 等编程语言进行操作。
我的距离矩阵如下,
enter image description here
我使用了经典的多维缩放功能(在 R 中)并获得了一个 2D 图,看起来像:enter image description here
但我正在寻找的是一个带有节点和在它们之间运行的加权边的图。

最佳答案

可能性 1
我假设您需要一个二维图,其中节点位置之间的距离与您的表 提供的相同.
在python中,你可以使用networkx对于此类应用。一般来说,有很多方法可以做到这一点,请记住,所有这些方法都只是近似值(因为一般情况下,不可能创建点的二维表示给定它们的成对距离)它们是某种应力最小化(或能量-minimization) 近似值,试图找到与提供的距离相似的“合理”表示。
作为示例,您可以考虑一个四点示例(应用正确的离散度量):

     p1 p2 p3 p4
  ---------------
  p1  0  1  1  1
  p2  1  0  1  1
  p3  1  1  0  1
  p4  1  1  1  0
通常,绘制实际的“图形”是多余的,因为您已经完全连接了一个(每对节点都已连接),因此只绘制点就足够了。
Python example
import networkx as nx
import numpy as np
import string

dt = [('len', float)]
A = np.array([(0, 0.3, 0.4, 0.7),
               (0.3, 0, 0.9, 0.2),
               (0.4, 0.9, 0, 0.1),
               (0.7, 0.2, 0.1, 0)
               ])*10
A = A.view(dt)

G = nx.from_numpy_matrix(A)
G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),string.ascii_uppercase)))    

G = nx.to_agraph(G)

G.node_attr.update(color="red", style="filled")
G.edge_attr.update(color="blue", width="2.0")

G.draw('distances.png', format='png', prog='neato')
在 R 中你可以试试 multidimensional scaling
# Classical MDS
# N rows (objects) x p columns (variables)
# each row identified by a unique row name

d <- dist(mydata) # euclidean distances between the rows
fit <- cmdscale(d,eig=TRUE, k=2) # k is the number of dim
fit # view results

# plot solution 
x <- fit$points[,1]
y <- fit$points[,2]
plot(x, y, xlab="Coordinate 1", ylab="Coordinate 2", 
  main="Metric  MDS",    type="n")
text(x, y, labels = row.names(mydata), cex=.7)
可能性2
您只想绘制带有标记边的图形
再次,networkx可以帮助:
import networkx as nx   

# Create a graph
G = nx.Graph()

# distances
D = [ [0, 1], [1, 0] ]

labels = {}
for n in range(len(D)):
    for m in range(len(D)-(n+1)):
        G.add_edge(n,n+m+1)
        labels[ (n,n+m+1) ] = str(D[n][n+m+1])

pos=nx.spring_layout(G)

nx.draw(G, pos)
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels,font_size=30)

import pylab as plt
plt.show()

关于matrix - 将距离矩阵可视化为图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18911994/

相关文章:

matlab - 有没有办法以更简单的方式将 MATLAB 中的多个 2x2 矩阵堆叠到多维数组中(例如,不使用 "cat"或 "reshape")?

matlab - 矩阵作为函数的输出

javascript - 显示组间交叉表的分组条形图

d3.js - 如何可视化两个图之间的差异

matrix - VR中变换矩阵的问题

java - 设置位图的旋转和位置

python - 将 Python 字典转换为 Word2Vec 对象

algorithm - 将无限值范围缩放到有限区间

python - 将 Matplotlib 图形保存为全屏图像

c++ - 二进制 '[' : no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion)