【问题标题】:keep the scaling while drawing a weighed networkx在绘制加权网络时保持缩放x
【发布时间】:2013-09-20 12:53:06
【问题描述】:

当我绘制一个加权网络时,它并不能真正代表距离方面的真实权重。我很好奇是否缺少任何参数或其他问题。

所以,我首先制作了一个模拟数据集,如下所示

from pylab import plot,show
from numpy import vstack,array
from numpy.random import rand
from scipy.cluster.vq import kmeans,vq
from scipy.spatial.distance import euclidean
import networkx as nx
from scipy.spatial.distance import pdist, squareform, cdist


# data generation
data = vstack((rand(5,2) + array([12,12]),rand(5,2)))
a = pdist(data, 'euclidean')

def givexy(index1D, VectorLength):
    return [index1D%VectorLength, index1D/VectorLength]


import matplotlib.pyplot as plt
plt.plot(data[:,0], data[:,1], 'o')
plt.show()

然后,我计算所有对之间的欧几里得距离,并将距离作为权重

G = nx.empty_graph(1)       
for cnt, item in enumerate(a):
    print cnt
    G.add_edge(givexy(cnt, 10)[0], givexy(cnt, 10)[1], weight=item, length=0)


pos = nx.spring_layout(G)
nx.draw_networkx(G, pos)
edge_labels=dict([((u,v,),"%.2f" % d['weight'])
         for u,v,d in G.edges(data=True)])
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
#~ nx.draw(G,pos,edge_labels=edge_labels)

plt.show()
exit()

您可能会得到不同的情节 - 由于未知原因,它是随机的。我的主要问题是节点的距离。例如节点 4 到 8 之间的距离是 0.82,但它看起来比节点 7 和 0 的距离更长。

任何提示? 谢谢,

【问题讨论】:

    标签: networkx


    【解决方案1】:

    弹簧布局没有明确使用权重作为距离。较高权重的边缘通常会产生较短的边缘。

    如果你想明确指定位置,你可以这样做:

    from numpy import vstack,array
    from numpy.random import rand
    from scipy.spatial.distance import euclidean, pdist
    import networkx as nx
    import matplotlib.pyplot as plt
    
    # data generation
    data = vstack((rand(5,2) + array([12,12]),rand(5,2)))
    a = pdist(data, 'euclidean')
    
    def givexy(index1D, VectorLength):
        return [index1D%VectorLength, index1D/VectorLength]
    
    
    plt.plot(data[:,0], data[:,1], 'o')
    
    G = nx.Graph()
    for cnt, item in enumerate(a):
        print cnt
        G.add_edge(givexy(cnt, 10)[0], givexy(cnt, 10)[1], weight=item, length=0)
    
    pos={}
    for node,row in enumerate(data):
        pos[node]=row
    nx.draw_networkx(G, pos)
    plt.savefig('drawing.png')
    

    【讨论】:

    • 感谢它有效 - 我想在这里问一些奇怪的事情。当我过滤边缘(小于 1 的边缘)时,为了显示更短的交互,一些短交互丢失了。并且这两组之间没有完全的相互联系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多