简体   繁体   中英

Create NetworkX weighted Graph based on vertices location

I have edge information organised in a way that shows the edge's location within a regular-type Graph; where a regular graph is defined as one that looks like a "checker-board". Here is an example of how the data is organised:

(7, 3) (6, 3) 1.0
(7, 3) (8, 3) 1.0
(7, 3) (8, 2) 1.41421356237
(7, 3) (6, 4) 1.41421356237
(7, 3) (7, 4) 1.0
(7, 3) (6, 2) 1.41421356237
(7, 3) (7, 2) 1.0
(7, 3) (8, 4) 1.41421356237

Here, column 1 represents the first point's location (eg 7 columns over and 3 rows down for the very first point), column 2 represents the adjacent point, and column 3 represents edge weight value between the two points. The provided example shows all possible adjacent paths (including diagonals) for the point at location (7,3).

My code to create a graph with these edges looks as such:

import networkx as nx
edgelist = r'C:\filepath'
edges = nx.read_weighted_edgelist(edgelist, create_using= nx.Graph(), nodetype= int)
nx.draw_networkx(edges)

I am not getting an error but I am only receiving an empty output. Any thoughts on how to correct this? I am using Python 27. Thanks!

The node identity is, in principle, independent of its position. You could simplify the problem by creating a dummy identity for each node, and keep the node position stored in a different data structure that you then use when drawing the graph. For example, you could do the following:

import numpy as np
import matplotlib.pyplot as plt
import re
import networkx as nx

def load(fpath):
    # adapated from: https://stackoverflow.com/a/48097465/2912349
    data = []
    pattern='\((\d+, \d+)\)'
    with open(fpath, 'r') as f:
        for line in f:
            matches = re.findall(pattern, line)
            source, target = [tuple(map(lambda x:int(x),item.split(','))) for item in matches]
            weight = float(line.split(' ')[-1])
            data.append((source, target, weight))
    return data

data = load('test_grid.txt')
# print data

# determine unique nodes
sources = [source for source, _, _ in data]
targets = [target for _, target, _ in data]
coordinates = set(sources + targets)

# create mappings from node -> coordinate and vice versa
pos     = {ii : xy for ii, xy in enumerate(coordinates)}
inverse = {xy : ii for ii, xy in enumerate(coordinates)}

# create a more conventional edge list
edges = []
for (source_coord, target_coord, weight) in data:
    edge = (inverse[source_coord], inverse[target_coord], weight)
    edges.append(edge)

# create graph and plot
g = nx.Graph()
g.add_weighted_edges_from(edges)
nx.draw(g, pos)

在此处输入图片说明

This script assumes that your graph is stored in a text file at test_grid.txt . Change the path as necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM