Search code examples
pythongraphgraphviz

how can I control subgraphs distance in python graphviz?


I tried visualize a three layer Neural Network in Python using Graphviz, in the first step I wrote below code:

import graphviz
n = graphviz.Digraph(comment='The Round Table',node_attr={'shape':'circle'},
                     edge_attr={},graph_attr={'splines':'line','nodesep':'2', 'ranksep':'1.3',})
layer_nodes = 3
layers = 3

for layer in range(layers):
    edges = []
    for node in range(layer_nodes):
        if node!=layer_nodes-1:
            edges.append((str(layer)+str(node),str(layer)+str(node+1)))
    print(edges)        
    with n.subgraph(name='cluster_'+str(layer)) as c:#!name just should be cluster_#
        c.attr(style='filled', color='lightgrey')
        c.node_attr.update(style='filled', color='white')
        c.edges(edges)
        c.edge_attr.update(color='lightgrey',arrowhead='none')
        c.attr(label='layer '+str(layer))

and output: enter image description here

in the next step I tried draw edges using below code:

for layer in range(layers):
    for node in range(layer_nodes):
        for next_layer in range(layer_nodes):
            if layer!=2:
                n.edge(str(layer)+str(node),str(layer+1)+str(next_layer),
                color='red',constraint='false')

and output:enter image description here

in the final output, subgraphs distance are not equal, I tried set dsitances using ranksep and nodesep but I was not successful, please help me to control subgraphs distance.


Solution

  • Here is a Graphviz-only solution. I hope it helps.

    digraph 3 {
      rankdir=LR  // ranks left to right
      splines=false
      ranksep=1.3
    
      node[ shape=circle]
    
      subgraph cluster1 {
      label="layer 0"
      bgcolor=grey
    
      // group to keep top-down order
      {rank=same 00 [group=x0] 01[group=x1] 02[group=x2]}
      }
      subgraph cluster2 {
      label="layer 1"
      bgcolor=grey
      {rank=same 10[group=x0] 11[group=x1] 12[group=x2]}
      }
      subgraph cluster3 {
      label="layer 2"
      bgcolor=grey
      {rank=same 20[group=x0]  21[group=x1] 22[group=x2]}
      }
    
      edge [color=red]
      00 -> {10 11 12}
      01 -> {10 11 12}
      02 -> {10 11 12}
    
      10 -> {20 21 22}
      11 -> {20 21 22}
      12 -> {20 21 22}
    }
    

    enter image description here