How can I optimize GraphViz output width?

MickaelFM picture MickaelFM · Jun 19, 2011 · Viewed 26.4k times · Source

I make graphs that have huge width ratio: they are 51706 x 503 pixels in size. How can I tell GraphViz to optimize width ?

Note 1: the graph is in fact a tree with each node having a lot of children. Here is a sample.

Note 2: I think I use dot :)

Note 3: Here is the Ruby code

def graph_node(n, parent=nil, depth=0)
  #print n, " "
  gn = @g.add_node(n.object_id.to_s, :label=>n.to_graphviz, :shape=>"Mrecord")
  if parent
    e = @g.add_edge(parent, gn)
  end
  if n == @current_pos_node
    gn[:color] = "brown3"
    gn[:style] = "filled"
  elsif @s.tree.pv(@current_pos_node).include?(n)
    gn[:color] = "cadetblue"
    gn[:style] = "filled"
  elsif @s.tree.pv(@root).include?(n)
    gn[:color] = "yellow"
    gn[:style] = "filled"
  end
  return if !n.children # or depth == 2
  i = 0
  for c in n.children
    graph_node(c, gn, depth+1)
    i += 1
    #break if i > 2
  end
end

def graph(name="tree", root_node=@current_pos_node)
  @g = GraphViz::new("G")
  #@g['sep'] = "10,100"
  #@g["overlap"] = "compress"
  #@g["rankdir"] = "BT"
  #@g["ratio"] = "0.9"
  @g["size"] = "350,500"
  graph_node(root_node)
  @g.output(:svg => "#{name}.svg")
end

Answer

marapet picture marapet · Jun 22, 2011

In case the graph consists of several trees which are not connected, you could split them up (as mentioned in Graphviz: break flat but sparsely connected graph into multiple rows?)

Depending on your particular graph, you may obtain a smaller graph when using

ratio="compress"

(You'll have to specify size though)

For detailed optimizations on a specific graph, you may add rank attributes and distribute the nodes manually on different ranks.


Edit:

There is a graphviz tool called unflatten which seems to exist exactly for this purpose :

unflatten is a preprocessor to dot that is used to improve the aspect ratio of graphs having many leaves or disconnected nodes. The usual layout for such a graph is generally very wide or tall. unflatten inserts invisible edges or adjusts the minlen on edges to improve layout compaction.

Never had the need to use it, but I think it's worth a try.