Wednesday, March 12, 2008

gruff



I was building a dynamic bar graph into the Orchive website, and decided to try Gruff Graphs for it. Since I tried it last, it's really matured with a really nice Ruby on Rails plugin. It has fairly good API documentation, but to really find out how to use it, look at the test code in the gem, for example /usr/lib/ruby/gems/1.8/gems/gruff-0.2.9/test/test_bar.rb for the Bar graph.

On the plugin page, he shows a really neat way to have a controller action use send_data to send a dynamically generated png back to the browser, but doesn't really explain how to use this in your view. I found a blog post that shows how to do this, you just make an action like:


def year_graph

g = Gruff::Bar.new("700x400")
g.title = "Percent of Orca song digitized per Year"

g.labels = Year.labels
g.data(:Test, Year.data, "#008B00" )

g.hide_legend = true
g.minimum_value = 0
g.maximum_value = 100

send_data(g.to_blob,
:disposition => 'inline',
:type => 'image/png',
:filename => "years.png")
end


and then in your view, call this action as the target of an img tag:


<div class="year-graph">
<%= image_tag "/main/year_graph" %>
</div>


I then use some CSS to center this in the page:


.year-graph {
margin-left: auto;
margin-right: auto;
width: 700px;
}


The end result looks like: