简体   繁体   English

使用 Networkx python 将节点名称放入图表

[英]Put nodes names to a graph with Networkx python

I created a graph G (network library) through the adjacency matrix A (numpy matrix) that stores the weights of the links.我通过存储链接权重的邻接矩阵 A(numpy 矩阵)创建了一个图 G(网络库)。

import numpy as np
import networkx as nx

A = np.loadtxt('SM_waste.csv',delimiter=';')
G = nx.from_numpy_matrix(A, parallel_edges=False, create_using=None)

I also have the list of the names of the nodes but I don't know how to assign the name to each node.我也有节点名称列表,但我不知道如何将名称分配给每个节点。 How can I do?我能怎么做?

You can loop over the nodes and append the label from the row index.您可以遍历节点并从行索引附加标签。

Example with faker data:伪造数据的示例:

import faker
import networkx as nx

for node in G.nodes():
    G.nodes[node]['name'] = faker.Faker().name()

G.nodes(data=True)

With some fake names this outputs for ten nodes a NodeDataView looking like so使用一些假名称,这会为十个节点输出一个 NodeDataView,如下所示

>>> NodeDataView({0: {'name': 'Kayla Martin'}, 1: {'name': 'Billy Knight'}, 2: {'name': 'Joshua Landry'}, 3: {'name': 'Jessica Perez'}, 4: {'name': 'Emily Garcia'}, 5: {'name': 'Stephen Foster'}, 6: {'name': 'Timothy Howell'}, 7: {'name': 'Stephanie Gonzales'}, 8: {'name': 'Maurice Miller'}, 9: {'name': 'Emily Caldwell'}, 10: {'name': 'Amy Rice'}

In your case this could look something like:在您的情况下,这可能类似于:

import numpy as np
import networkx as nx

A = np.loadtxt('SM_waste.csv',delimiter=';')
G = nx.from_numpy_matrix(A, parallel_edges=False, create_using=None)

labels = ["<list of your row labels here indexed according to the adjacency matrix>"]

for idx, node in enumerate(G.nodes()):
    G.nodes[node]['label'] = labels[idx]

Note that the above solution probably won't work if you call G.nodes() with data=True .请注意,如果您使用data=True调用G.nodes() ,上述解决方案可能不起作用。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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