如何便捷为networkx的DiGraph生成层级结构节点标签?
生成networkx有向图层级标签的实现方案
效果示例

实现思路
你需要的层级标签本质是以根节点为起点的层级路径索引,规则为:
- 根节点标签为空元组
- 每个子节点的标签为父节点标签追加「该子节点在同级兄弟节点中的排序索引」
我们可以通过BFS(广度优先遍历)自动遍历全图生成对应标签,不需要手动构造。
完整实现代码
标签生成函数
import networkx as nx from collections import deque def generate_hierarchical_labels(G: nx.DiGraph): # 筛选所有入度为0的根节点 roots = [node for node, in_degree in G.in_degree() if in_degree == 0] labels = {} # BFS队列元素格式:(当前节点, 父节点的标签) queue = deque() for root in roots: labels[root] = () queue.append((root, ())) while queue: parent_node, parent_label = queue.popleft() # 子节点默认按节点编号升序排序,可根据需求调整排序规则 children = sorted(G.successors(parent_node)) for idx, child_node in enumerate(children): child_label = parent_label + (idx,) labels[child_node] = child_label queue.append((child_node, child_label)) return labels
原有代码调用示例
import matplotlib.pyplot as plt from networkx.drawing.nx_agraph import graphviz_layout H = nx.DiGraph([(0, 1), (0, 12), (1, 2), (1, 3), (3, 4), (3, 7), (4, 5), (4, 6), (7, 8), (7, 9), (9, 10), (9, 11), (12, 13), (12, 14)]) # 新增:自动生成标签,输出结果和你手动构造的完全一致 labels = generate_hierarchical_labels(H) kwargs = {'pos': graphviz_layout(H, prog='dot'), 'nodelist':[], 'with_labels':True, 'bbox': dict(boxstyle='round,pad=0.7')} fig = plt.figure(figsize=(20,10)) fig.add_subplot(1, 2, 1) nx.draw(H, **kwargs) fig.add_subplot(1, 2, 2) nx.draw(H, **kwargs, labels=labels) plt.show()
自定义说明
- 调整子节点排序:修改
children = sorted(G.successors(parent_node))的排序逻辑即可,比如按节点属性排序、逆序排列等 - 多根节点兼容:如果你的有向图存在多个入度为0的根节点,函数会自动为每个根节点的分支生成独立的层级标签
内容的提问来源于stack exchange,提问作者mathfux
相关产品推荐
相关产品推荐

