如何用Python将GV文件拆分为含无重叠子图的GV文件?
图结构
我有一个包含3个子图的GV文件:
cluster_1cluster_2cluster_3
Final_Graph.gv的源码:
digraph Final_Graph { graph [center=true rankdir=LR ratio=compress size="15,10"] a b c d a -> b [label = 1] a -> c [label = 2] a -> d [label = 3] b -> d [label = 4] c -> d [label = 5] subgraph cluster_1{ color=lightgrey style=filled label="A" a b } subgraph cluster_2{ color=lightgrey style=filled label="B" a b } subgraph cluster_3{ color=lightgrey style=filled label="C" c d } }
渲染效果:
需求
我希望生成其他GV文件,其中的子图彼此无重叠(即子图间没有相同节点,比如第一个文件可以包含cluster_1和cluster_3,第二个文件包含cluster_2和cluster_3)。
代码实现
我使用以下Python函数完成该任务:
import networkx as nx import itertools def draw_graph_combinations(): # Load the original graph G = nx.drawing.nx_agraph.read_dot("Final_Graph.gv") # Create an empty dictionary to store the subgraphs subgraphs = {} # Iterate over the edges of the graph for u, v, data in G.edges(data=True): label = data.get("label") if label not in subgraphs: subgraphs[label] = nx.DiGraph() for node in G.nodes: # Add the node to each subgraph for label, subgraph in subgraphs.items(): subgraph.add_node(node) for label, subgraph in subgraphs.items(): for edge in G.edges: subgraph.add_edge(edge[0], edge[1]) # Get all combinations of subgraphs combinations = itertools.combinations(subgraphs.items(), len(subgraphs)) # Iterate over the combinations for i, subgraph_items in enumerate(combinations): combined_subgraph = nx.DiGraph() for label, subgraph in subgraph_items: combined_subgraph = nx.compose(combined_subgraph, subgraph) nx.drawing.nx_agraph.write_dot(combined_subgraph, f"combined_subgraph_{i}.gv")
问题
运行该函数后,生成的文件只包含原文件的节点和边,没有保留子图结构。
求助
有没有Python方法可以将该GV文件拆分为包含无重叠子图的多个GV文件?
内容的提问来源于stack exchange,提问作者Hoang Cuong Nguyen
相关产品推荐
相关产品推荐

