有没有办法将位置元组作为属性添加到networkx中的已创建节点? [英] Is there a way to add a tuple of position as an attribute to a created node in networkx?

查看:97
本文介绍了有没有办法将位置元组作为属性添加到networkx中的已创建节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取要放入图中的所有节点的位置.当前的目标是创建所有具有xy坐标的节点.

I'm trying to get the position of all the nodes that are being made into my graph. The current goal is to create all the nodes which possess an x and y coordinate.

我正在阅读的内容是关于使用add_nodes_from()时的属性的信息,并可能为我的节点创建一个position属性.对我来说,阅读一些文档和另一个StackOverflow是不成功的.

What I was reading is about attributes when using add_nodes_from() and possibly create a position attribute for my nodes. Reading a little bit of documentation and another StackOverflow is unsuccessful for me.

ex.txt文件:

a2a 5 0
##start
a0 1 2
##end
a1 9 2
3 5 4

python文件:

import re
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

def file_parsing(file_path):
    cnt = 0
    output_list = []

    with open(file_path, 'r') as fp:
        for line in fp:
            cnt += 1
            #checks for the room name and coordinates
            if re.match('([^\s#]{1,10}) (\d+) (\d+)', line, re.MULTILINE):
                output_list.append(line.strip().split(' '))
            #checks for start
            if line.startswith('##start'):
                output_list.append(next(fp, '').strip().split())
            #checks for start
            if line.startswith('##end'):
                output_list.append(next(fp, '').strip().split())
    room_name = [item[0] for item in output_list]
    x_coord = [int(item[1]) for item in output_list]
    y_coord = [int(item[2]) for item in output_list]
    x_y = list(zip(x_coord, y_coord))
    return (room_name, output_list, x_y)

rooms, room_coords, xpos_ypos = file_parsing('ex.txt')
print("Room information: ", room_coords)
print("X and Y position as tuple list: ", xpos_ypos)
DG = nx.DiGraph()
DG.add_nodes_from(rooms, pos = xpos_ypos)
pos = nx.get_node_attributes(DG, 'pos')
print(pos)

plt.figure()

nx.draw_networkx(DG)

如您所见,我的zip文件中有xpos_ypos,它创建了一个元组列表.而且我的迭代顺序很重要,因为第一个房间将从第一个元组开始具有x和y坐标.

As you see, I have my xpos_ypos in a zip, which creates a list of tuples. And my order of iteration matters because the first room will have the x and y coordinates from the first tuple.

例如,我的第一个房间是a2a,其坐标为(5, 0).如果(1, 2),房间a0将具有坐标.现在,如果要一遍又一遍地为每个房间做同样的事情:如何将房间坐标属性添加到每个房间?就我而言,我得到的是字典:

For example, my first room is a2a which will have the coordinate of (5, 0). Room a0 will have coordinates if (1, 2). Now, if I want to do the same thing over and over for each room: how could I add the room coordinates attributes to each room? In my case, I'm getting a dictionary as a result:

{'a2a': [(5, 0), (1, 2), (9, 2), (5, 4)], 'a0': [(5, 0), (1, 2), (9, 2), (5, 4)], 'a1': [(5, 0), (1, 2), (9, 2), (5, 4)], '3': [(5, 0), (1, 2), (9, 2), (5, 4)]}

,这是输出draw_networkx(DG):

推荐答案

您的代码无法正常工作,因为您不正确地传递了职位. 我对您的函数进行了一些更改,以便它返回一个字典,其中键为节点名,值为[x, y]坐标.像这样

Your code is not working because you are passing the positions incorrectly. I have made a few changes to your function so that it returns a dictionary with keys as the node names and values as [x, y] co-ordinates. Something like this

{'a2a': (5, 0), 'a0': (1, 2), 'a1': (9, 2), '3': (5, 4)}

然后我从返回的字典和上面的字典到nx.draw_networkx函数的pos属性创建图形.

Then I created the graph from the returned dictionary and the above dictionary to the pos attribute of nx.draw_networkx function.

import re
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
%matplotlib inline
def file_parsing(file_path):
    cnt = 0
    output_list = []

    with open(file_path, 'r') as fp:
        for line in fp:
            cnt += 1
            #checks for the room name and coordinates
            if re.match('([^\s#]{1,10}) (\d+) (\d+)', line, re.MULTILINE):
                output_list.append(line.strip().split(' '))
            #checks for start
            if line.startswith('##start'):
                output_list.append(next(fp, '').strip().split())
            #checks for start
            if line.startswith('##end'):
                output_list.append(next(fp, '').strip().split())
    room_name = [item[0] for item in output_list]
    x_coord = [int(item[1]) for item in output_list]
    y_coord = [int(item[2]) for item in output_list]
    x_y = list(zip(x_coord, y_coord))

    #--------------Changes start from here -----------#

    pos_dict = dict(zip(room_name, x_y))
    return pos_dict

room_pos_dict = file_parsing('ex.txt')
G = nx.Graph()
G.add_nodes_from(room_pos_dict.keys())
nx.set_node_attributes(G, room_pos_dict, 'pos')
nx.draw_networkx(G, pos=nx.get_node_attributes(G, 'pos'))

这篇关于有没有办法将位置元组作为属性添加到networkx中的已创建节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆