Sparklines

If you use Google Analytics, you have seen Sparklines at work. Sparklines, as described by Edward Tuft, are intense, simple word-sized graphics. These tiny, sometimes ambiguous, graphs can give a needed overview of a path of a set of numbers, even without a reference point. They look something like this and they can give the user a sense of history at a quick glance… as they glaze over the list of numbers next to it.

I wanted to use Sparklines on a project I had been working on in Ruby on Rails. There are plenty of resources for installing the Sparkline gem, but I couldn’t find much on actually implementing them. I created a quick script that could render sparklines with variables I could send from the URL. (NOTE: This could probably be written better, but it worked for me.)

You will need to get the RMagick and Sparkline gems:

$ gem install rmagick
$ gem install sparklines

Here is what your action (apps/controllers/controller_name.rb) would look like:

def sparkline
  require 'RMagick'
  require 'sparklines'
  respond_to do |format|
    data = params[:d]
    params[:h].blank? ? (height = 40) : (height = params[:h])
    params[:s].blank? ? (step = 4) : (step = params[:s])
    params[:c].blank? ? (color = "2A5DB8") : (color = params[:c])
    params[:t].blank? ? (type = "smooth") : (type = params[:t])

    data = "0" if params[:d].blank?
    format.png do
      sparkline = Sparklines.plot_to_image(
                                    data.split(",").collect { |d| d.to_i },
                                    :type => type,
                                    :upper => 0,
                                    :above_color => "##{color}",
                                    :line_color => "##{color}",
                                    :step => step,
                                    :height => height
                                    )
      send_data sparkline.to_blob,  :filename => "sparkline.png",
                                    :disposition => 'inline',
                                    :type => "image/png"
    end
  end
end

Don’t forget to add the sparkline to your routes (config/routes.rb):

map.sparkline      '/sparkline', :controller => 'graphs', :action => 'sparkline'

About this entry