I'm using the ruby-graphviz gem and I'm trying to draw binary trees. I'd like to use the record shape so that each node can have a left, middle, and right field and, thus, if there are two edges leaving a node, the left and right edges can be distinguished.
I tried specifying the field by concatenating the field name like this: @node1.name + ":left"
But that did not work. What is the correct way of specifying the field?
require 'rubygems'
require 'graphviz'
@graph = GraphViz.new( :G, :type => :digraph )
@node1 = @graph.add_node("1",
"shape" => "record",
"label" => "<left>|<f1> 1|<right>" )
@node2 = @graph.add_node("2",
"shape" => "record",
"label" => "<left>|<f1> 2|<right>" )
@graph.add_edge(@node1.name + ":left", @node2)
# generate a random filename
filename = "/tmp/#{(0...8).map{65开发者_JAVA技巧.+(rand(25)).chr}.join}.png"
@graph.output( :png => filename )
exec "open #{filename}"
in the GraphViz documentation, you can see that a node ID must not begin with a digit. So if you change your code and replace the two nodes names (1 and 2) by any other ID beginning by a letter or an underscore, it works :
require 'rubygems'
require 'graphviz'
@graph = GraphViz.new( :G, :type => :digraph )
@node1 = @graph.add_node("A1",
"shape" => "record",
"label" => "<left>|<f1> 1|<right>" )
@node2 = @graph.add_node("A2",
"shape" => "record",
"label" => "<left>|<f1> 2|<right>" )
@graph.add_edge(@node1.name + ":left", @node2)
# generate a random filename
filename = "/tmp/#{(0...8).map{65.+(rand(25)).chr}.join}.png"
@graph.output( :png => filename )
exec "open #{filename}"
Maybe i need to replace GraphViz::Node#name by GraphViz::Node#id
Greg
Here's how I ended up doing it:
@graph.add_edge(@node1, @node2, :tailport => "left")
Your way of specifying node and field was wrong. Rather you should do:
@graph.add_edge({@node1.name=>"left"}, @node2)
Refer to the example coming with its source code at: https://github.com/glejeune/Ruby-Graphviz/blob/master/examples/sample07.rb
精彩评论