2

I generate a pydot graph with the following code

graph1 = pydot.Dot(graph_type='digraph') A = pydot.Node("A", style="filled", fillcolor="green") B = pydot.Node("B", style="filled", fillcolor="blue") graph1.add_node(A) graph1.add_node(B) graph1.add_edge(pydot.Edge(A,B)) graph1.write_png('graph1.png')

and my output is

graph1

and I generate a another pydot graph with the following code

graph2 = pydot.Dot(graph_type='digraph')
C = pydot.Node("C", style="filled", fillcolor="green")
D = pydot.Node("D", style="filled", fillcolor="blue")
graph2.add_node(C)
graph2.add_node(D)
graph2.add_edge(pydot.Edge(C,D))
graph2.write_png('graph2.png')

and my output is as follows.

graph2

My request is how to merge these 2 graphs(graph1 and graph2)? My expected output after merging as

merged graph

I tried with the following code, but, its not working..

graph3 = pydot.Dot(graph_type='digraph')
graph1_leaf = pydot.Node(graph1.get_node(B), style="filled", 
fillcolor="green")
graph2_root = pydot.Node(graph2.get_node(C), style="filled", 
fillcolor="green")

graph3.add_node(graph1_leaf)
graph3.add_node(graph2_root)
graph3.add_edge(pydot.Edge(graph1_leaf,graph2_root))
graph3.write_png('graph3.png')

Please guide me to merge these 2 graphs using pydot in python.. Thanks in advance..

user1999109
  • 421
  • 7
  • 19

1 Answers1

1

I couldn't find documentation describing joining 2 graphs. the common practice seems to be joining 2 sub graphs (clusters).

Here is answer that shows how it's done: Edges between two subgraphs in pydot

another helpful answer: Merge two dot graphs at a common node in python

Update, answer for edited question:

a few issues with your code:

  1. graph1.get_node(B) returns a list of nodes
  2. you are adding only the nodes and edge for connecting the graphs while you want all other nodes and edges

This code should return your wanted result:

graph3 = pydot.Dot(graph_type='digraph')
for node in graph1.get_nodes():
    graph3.add_node(node)
for node in graph2.get_nodes():
    graph3.add_node(node)
for edge in graph1.get_edges():
    graph3.add_edge(edge)
for edge in graph2.get_edges():
    graph3.add_edge(edge)
node_graph1 = graph1.get_node('B')[0]    
node_graph2 = graph2.get_node('C')[0]
graph3.add_edge(pydot.Edge(node_graph1,node_graph2))

graph3.write_png('/tmp/graph3.png')

hope it helps.

Elad
  • 221
  • 1
  • 6