1
刚开始学习网络科学,我是一名Python新手,因此即使阅读了一些有关networkx文档的知识,我仍然很难找出答案。我需要比较所有节点之间的距离,并在距离小于d的情况下生成边缘。如何比较节点1和节点(2 ... 99),然后比较节点2和节点(3 ... 99)等等。如果有更好的方法比O(n^2)请出示我。如何在网络中图形化网格节点
2)如何使用存储在node_loc {}中的x,y坐标将每个节点绘制到坐标平面上?
import random, math
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import pylab
# Calc distance given (x1,x2,y1,y2)
def distance(x1,x2,y1,y2):
return math.sqrt(((x2-x1)**2)+((y2-y1)**2))
# Generate coordinate value
def coord_val():
# node needs x and y coordinates (floats) from 0->100
return random.uniform(0.0,100.0)
def main():
# The distance that applies to link generation
d = 20
# Make a graph and name it
g = nx.Graph(name = "100x100 Field Random Network")
# Generate 100 nodes
for num in range(0,100):
# generate a dict with the node's location
node_loc = {'x': coord_val(), 'y': coord_val()}
# Add node with x,y dict
g.add_node(num,node_loc)
# Check node n against node n+1
for n,d in g.nodes(data=True):
if n == 99:
break
# I don't think this loop is correct
for rl in g.nodes(data=True):
# Don't go out of bounds on the loop
if n == 99:
break
# grab coordinates from nodes
y1=g.node[n]['y']
x1=g.node[n]['x']
y2=g.node[n+1]['y']
x2=g.node[n+1]['x']
# Check the distance, if < d, generate edge
if distance(x1,x2,y1,y2) < d:
# add edge
g.add_edge(n,n+1)
# plot
# draw_random draws it on a plane, but randomly :(
nx.draw_random(g,node_size=50)
plt.show()
if __name__ == '__main__':
main()
第2链接已死亡 – mbomb007