Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Created October 25, 2012 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanbsd/3953184 to your computer and use it in GitHub Desktop.
Save romanbsd/3953184 to your computer and use it in GitHub Desktop.
dendrogram
class DrawTree
require 'RMagick'
def drawdendrogram(tree, labels={}, file='tree.jpg')
h = tree.width * 20
w = 1200
scaling = (w-150).to_f / tree.depth
canvas = Magick::Image.new(w, h)
draw = Magick::Draw.new
draw.line(0,h/2,10,h/2)
drawnode(draw, tree, 10, h/2, scaling, labels)
draw.draw(canvas)
canvas.write(file)
canvas.destroy!
end
private
def drawnode(draw, tree, x, y, scaling, labels)
if tree.has_children?
heights = tree.children.collect {|c| c.width * 20}
top = y - heights.sum / 2
bottom = y + heights.sum / 2
# Line length
ll = scaling * (tree.respond_to?(:distance) ? tree.distance : 1.0)
# Vertical line from tree to children
draw.line(x, top + heights.first/2, x, bottom - heights.last/2)
sum = 0
heights.each do |h|
# Horizontal line to item
draw.line(x, top + sum + h/2, x + ll, top + sum + h/2)
sum += h
end
sum = 0
tree.children.each_with_index do |child,i|
drawnode(draw, child, x + ll, top + sum + heights[i]/2, scaling, labels)
sum += heights[i]
end
end
draw.text(x+5, y+5, labels[tree.id] || tree.name)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment