keep the scaling while drawing a weighed networkx

陌路散爱 提交于 2021-01-28 04:46:50

问题


when I draw a weighed networkx, it does not really represented the real weight in terms of distance. I was curious if there is any parameters that I am missing or some other problem.

so, I started by making a simulated dataset as following

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()

enter image description here

then, I calculate the euclidean distance among all pairs and use the distance as weight

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()

enter image description here

you might a get a different plot - because of unknown reason it is random. my main problem is the distance of nodes. for example the distance between node 4 to 8 is 0.82 but it looks longer than the distance of node 7 and 0.

any hint ? thank you,


回答1:


The spring layout doesn't explicitly use the weights as distances. Higher weight edges produce shorter edges in general.

Though if you want to specify the positions explicitly you can do that:

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')

enter image description here



来源:https://stackoverflow.com/questions/18917303/keep-the-scaling-while-drawing-a-weighed-networkx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!