Read more

Plotting graphs in Ruby with Gruff

Dominik Schöler
May 31, 2012Software engineer at makandra GmbH

Geoffrey Grosenbach has created Gruff for easily plotting graphs. It is written in pure Ruby and integrates with Rails applications.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

It provides features as automatic sizing of dots and lines (the more values, the thinner the graph's elements), custom or predefined themes, different styles (bar, line, dot and many more) and multiple graphs in one chart.

Installation

In your Gemfile:

gem 'rmagick', :require => false
gem 'gruff'

Then run bundle install (and don't forget to restart your development server.)

Usage

This is a common example for graph generation in Rails. Note that you have many configuration options at hand that are not documented. Github Show archive.org snapshot and the Gruff Docs Show archive.org snapshot will hint them.

Add a method like this to your model:

def graph(width=1000)
  graph = Gruff::Line.new(width) # the width of the resulting image
  graph.title = "Dataset"
  graph.hide_lines = true
  # graph.theme_odeo # available: theme_rails_keynote, theme_37signals, theme_odeo, or custom (fragile)
  graph.theme = {
    :colors => ['#3B5998'],
    :marker_color => 'silver',
    :font_color => '#333333',
    :background_colors => ['white', 'silver']
  }
  graph.data("data", datapoints.collect(&:amount))

  graph
end

If you want to save the graph as image (format is .png), call write('path/to/filename.png') on a graph. For displaying the graph in a view of you own application, you can just use a controller action like this:

def graph
  @post = Post.find(params[:id])

  send_data(@post.graph.to_blob, 
    :disposition => 'inline', 
    :type => 'image/png', 
    :filename => "datapoints_post_#{@post.id}.png")
end

Then simply set the action's path as an image's src:

<img src='<%= graph_post_path(@post)' %> />

Below, an example graph with about a thousand values and one with 20 values.

Posted by Dominik Schöler to makandra dev (2012-05-31 11:40)