如何在networkx中的网格上绘制节点

ter*_*ror 3 python matplotlib networkx

刚开始学习网络科学,我是 Python 的新手,所以即使在阅读了很多 networkx 文档之后,我也很难弄清楚这一点。我需要比较所有节点之间的距离,并在距离小于 d 的情况下生成一条边。

1)如何将节点 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()
Run Code Online (Sandbox Code Playgroud)

yat*_*atu 5

NetworkXnx.grid_2d_graph一个Graph 生成器,它返回mxn节点的二维网格图,每个节点都连接到其最近的邻居。默认情况下,它的标签将是网格的坐标

如果我们有兴趣将节点作为坐标,我们可以旋转位置,使原点位于左上角。否则,您可以保持原样。下面是一个例子:

import networkx as nx
from matplotlib import pyplot as plt

G = nx.grid_2d_graph(3,3)

plt.figure(figsize=(6,6))
pos = {(x,y):(y,-x) for x,y in G.nodes()}
nx.draw(G, pos=pos, 
        node_color='lightgreen', 
        with_labels=True,
        node_size=600)
Run Code Online (Sandbox Code Playgroud)

                            在此处输入图片说明

请注意,nx.grid_2d_graph将生成具有任意大m和 的网格图n,通过定位标签,您还可以像上面一样绘制坐标网格:

                    在此处输入图片说明


Ari*_*ric 1

看一下networkx随机几何图形生成器,以实现像您正在寻找的图形https://github.com/networkx/networkx/blob/master/networkx/generators/geometric.py#L79 有一个例子显示输出以及如何在此处绘制它https://networkx.github.io/documentation/stable/tutorial.html#drawing-graphs