O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.5. Adding Graphical Context with Sparklines

Problem

You want to display a small bit of statistical context—a trend or a set of percentages—in the middle of a piece of text, without breaking up the flow of the text.

Solution

Install the sparklines gem (written by Geoffrey Grosenbach)and create a sparkline: a tiny embedded graphic that can go next to a piece of text without being too intrusive. If you're creating an HTML page, the image doesn't even need to have its own file: it can be embedded directly in the HTML.

This code creates a sparkline for a company's stock price, and embeds it in HTML after the company's stock symbol:

	require 'rubygems'
	require ' 
sparklines'
	require 'base64'

	def embedded_sparkline
	  %{<img src="data:image/png;base64,#{Base64.encode64(yield)}">}
	end

	# This method scales data so that the smallest item becomes 0 and the
	# largest becomes 100.
	def scale(data)
	  min, max = data.min, data.max
	  data.collect { |x| (x - min) / (max - min) * 100}
	end

	# Randomly generate closing prices for the past month.
	prices = [rand(10)]
	30.times { prices << prices.last + (rand - 0.5) }

	# Generate HTML containing a stock graph as an embedded sparkline.
	sparkline = embedded_sparkline { Sparklines.plot(scale(prices)) }
	open('stock.html', 'w') do |f|
	  f << "Is EvilCorp (NASDAQ:EVIL #{sparkline}) poised for a comeback?"
	end

This code generates HTML that renders as shown in Figure 12-5.

A stock price history sparkline

Figure 12-5. A ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required