networkx怎么给节点添加标签


import networkx as nx
import matplotlib.pyplot as plt


# 数据准备
G = nx.DiGraph(with_labels=True)  # 单边有向图

G.add_edges_from([(1,2), ('x','y')]) # 一次性添加多条边
nx.draw(G)        # 简单画一下


plt.axis("off")           # 去掉边框
plt.show()

img

可以通过 nx.set_node_attributes() 给节点添加标签,具体实现如下:

import networkx as nx
import matplotlib.pyplot as plt
 
# 数据准备
G = nx.DiGraph(with_labels=True)  # 单边有向图
G.add_edges_from([(1,2), ('x','y')]) # 一次性添加多条边
 
# 添加节点标签
labels = {1: 'A', 2: 'B', 'x': 'C', 'y': 'D'}
nx.set_node_attributes(G, labels, 'label')
 
# 绘制图形
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_labels(G, pos, labels=nx.get_node_attributes(G, 'label'))
plt.axis("off")
plt.show()


其中,nx.set_node_attributes() 的三个参数分别为图对象、标签字典和标签名称。在绘制图形时,使用 nx.draw_networkx_labels() 绘制节点标签。


# 顶点(node)的操作
G1.add_node(1)  # 向 G1 添加顶点 1
G1.add_node(1,name='n1',weight=1.0)  # 添加顶点 1,定义 name, weight 属性
G1.add_node(2,date='May-16') # 添加顶点 2,定义 time 属性
G1.add_nodes_from([3, 0, 6], dist=1)  # 添加多个顶点:306
# 查看顶点和顶点属性
print(G1.nodes())  # 查看顶点
# [1, 2, 3, 0, 6]
print(G1._node)  # 查看顶点属性
# {1: {'name': 'n1', 'weight': 1.0}, 2: {'date': 'May-16'}, 3: {'dist': 1}, 0: {'dist': 1}, 6: {'dist': 1}}