【问题标题】:How to graph nodes on a grid in networkx如何在networkx中的网格上绘制节点
【发布时间】:2020-06-03 05:51:20
【问题描述】:

刚开始学习网络科学,我是 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()

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    NetworkXnx.grid_2d_graph,一个Graph generator,它返回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)
    

                               

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

                        

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-29
        • 2018-08-26
        相关资源
        最近更新 更多