如何在Networkx中的网格上绘制节点图 [英] How to graph nodes on a grid in networkx
问题描述
刚开始学习网络科学,而且我是Python的新手,所以即使在阅读了很多networkx文档之后,我仍然很难弄清楚这一点.我需要比较所有节点之间的距离,并在距离小于 d 的情况下生成一条边.
Just started learning Network Science and I'm a novice in Python so I've been having a hard time figuring this out even after reading a good bit of the networkx documentation. I need to compare the distance between all the nodes and generate an edge in the event the distance is less than d.
1) 如何将节点 1 与节点 (2...99) 进行比较,然后将节点 2 与节点 (3...99) 等进行比较.如果有比 O(n^2)请告诉我.
1) How to I compare node 1 to nodes (2...99) and then compare node 2 to nodes (3...99), etc. If there's a better way to do it than O(n^2) please show me.
2) 如何使用 node_loc{} 中存储的 x,y 坐标将每个节点绘制到坐标平面?
2) How can I use the x,y coordinates stored in node_loc{} to graph each node to a coordinate plane?
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()
推荐答案
查看 networkx 随机几何图生成器,以实现您正在寻找的图 https://github.com/networkx/networkx/blob/master/networkx/generators/geometric.py#L79有一个示例显示了输出以及如何在此处绘制它 https://networkx.github.io/documentation/stable/tutorial.html#drawing-graphs
Take a look at the networkx random geometric graph generator for an implementation of a graph like you are looking for https://github.com/networkx/networkx/blob/master/networkx/generators/geometric.py#L79 There is an example that shows the output and how to draw it here https://networkx.github.io/documentation/stable/tutorial.html#drawing-graphs
这篇关于如何在Networkx中的网格上绘制节点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!