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

No credit card required

# 12.4. Graphing Data

## Problem

You want to convert a bunch of data into a graph; usually a line chart, bar chart, or pie chart.

## Solution

Use the Gruff library, written by Geoffrey Grosenbach. Install the ` gruff` gem and build a `Gruff` object corresponding to the type of graph you want (for instance, ```Gruff::Line, Gruff::Bar,or Gruff::Pie)```. Add a dataset to the graph by passing `data` a label and an array of data points.

Here's code to create a graph that compares the running times of different sorts of algorithms:

```	require 'rubygems'
require 'gruff'

g = Gruff::Line.new(600)                 # The graph will be 600 pixels wide.
g.title = 'Algorithm running times'
g.theme_37signals                        # The best-looking theme, in my opinion.

range = (1..101)
g.data('Constant', range.collect { 1 })
g.data('O(log n)', range.collect { |x| Math::log(x) / Math::log(2) })
g.data('O(n)', range.collect { |x| x })
g.data('O(n log n)', range.collect { |x| x * Math::log(x) / Math::log(2) })

g.labels = {10 => 'n=10', 50 => 'n=50', 100 => 'n=100' }
g.write('algorithms.png')```

Figure 12-3 shows the graph it produces.

Here's code to create a pie chart (shown in Figure 12-4). Note that the numbers given for the datasets don't have to add up to 100. Gruff automatically scales the the pie chart to display the right proportions.

`	p = Gruff::Pie.new p.theme_monochrome p.title = "Survey: the value of pi" p.data('"About three"', ...`

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

No credit card required