使用networkx绘制嵌套字典网络如何展示最内层节点
原因说明
你用from_dict_of_dicts没展示最内层节点是因为这个方法仅支持两层结构的字典(结构为{源节点: {目标节点: {边属性}}}),你传入的多层嵌套字典里的最内层键会被识别为边的属性,不会被当成独立节点处理。
解决方法
你可以递归遍历整个嵌套字典,手动把每一层的父子节点关系添加到网络图中,直到遍历到最内层非字典结构停止即可,示例代码如下:
import networkx as nx import matplotlib.pyplot as plt # 你的嵌套字典 tdict={'a1':{ 'aa1':{'aaa101':{'information'},'aaa201':{'information'}}, 'aa2':{'cca101':{'information'},'aca201':{'information'}}, 'ab1':{'aasdfaa101':{'information'},'aadaa201':{'information'}} }, 'a2':{ 'ab1':{'aasdfaa101':{'information'},'aadaa201':{'information'}}, 'ab2':{'zz101':{'information'},'azz201':{'information'}}, 'ac2':{'aaa101':{'information'},'aaa201':{'information'}} }, 'a3':{ 'ac1':{'aaa101':{'information'},'aaa201':{'information'}}, 'ac2':{'aaa101':{'information'},'aaa201':{'information'}} }} # 初始化图,用有向图更能体现层级从属关系,需要无向图替换为nx.Graph即可 G = nx.DiGraph() # 递归遍历函数:添加父节点到子节点的边 def add_edges(parent_node, child_content): if not isinstance(child_content, dict): return for child_node, next_content in child_content.items(): G.add_edge(parent_node, child_node) # 子节点内容还是字典的话继续递归遍历 add_edges(child_node, next_content) # 从最外层根节点开始遍历 for root_node in tdict: add_edges(root_node, tdict[root_node]) # 绘图 plt.figure(figsize=(12, 8)) # 固定随机种子保证每次运行布局一致 pos = nx.spring_layout(G, seed=42) nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=1500, font_size=10, edge_color='gray') plt.show()
运行上述代码即可在网络图中展示所有层级的节点,包含aaa101、zz101这类最内层键。
内容的提问来源于stack exchange,提问作者noob
相关产品推荐
相关产品推荐

