python - 根据顶点位置创建 NetworkX 加权图
问题描述
我的边缘信息以显示边缘在常规类型图表中的位置的方式组织;其中,常规图被定义为看起来像“棋盘”的图。以下是如何组织数据的示例:
(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
在这里,第 1 列代表第一个点的位置(例如,第一个点在上面 7 列和下面 3 行),第 2 列代表相邻点,第 3 列代表两个点之间的边缘权重值。提供的示例显示了位置 (7,3) 处的点的所有可能的相邻路径(包括对角线)。
我用这些边创建图形的代码如下所示:
import networkx as nx
edgelist = r'C:\filepath'
edges = nx.read_weighted_edgelist(edgelist, create_using= nx.Graph(), nodetype= int)
nx.draw_networkx(edges)
我没有收到错误,但我只收到一个空输出。关于如何纠正这个问题的任何想法?我正在使用 Python 27。谢谢!
解决方案
原则上,节点身份与其位置无关。您可以通过为每个节点创建一个虚拟身份来简化问题,并将节点位置存储在不同的数据结构中,然后在绘制图形时使用该结构。例如,您可以执行以下操作:
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)
此脚本假定您的图形存储在一个文本文件中test_grid.txt
。根据需要更改路径。
推荐阅读
- ios - 无法卸载 Xcode 13 Beta
- python - 更新excel文件功能
- javascript - 在 Array.prototype.sort() 中执行回调比较函数后会发生什么?
- javascript - 猫鼬中的 findOne 返回空对象,然后返回正确的对象
- javascript - 需要单行显示 JSON 数据,可读性强
- mongodb - 子文档数组的 MongoDB 唯一部分索引
- vue.js - 如何阻止 Tailwind CSS 清除本地开发环境中的类?
- powerbi - 有没有办法可以将 power bi 报告导出到 excel 而不会丢失 power bi 报告的格式和内容?
- python - python:如何显示文本文件的数据
- python - 如何记录所有 kafka 主题/事件