1

Generate a graph using Gruff

http://feeds.dzone.com

This Ruby code produced a graph using gruff. The output shows a line graph [twitxr.com] for the different fruits. Source code origin: Gruff Update With Bar Graphs | Ruby on Rails for Newbies [rubyonrails.com]

require 'gruff'

g = Gruff::Line.new
g.title = "My Graph"

g.data("Apples", [1, 2, 3, 4, 4, 3])
g.data("Oranges", [4, 8, 7, 9, 8, 9])
g.data("Watermelon", [2, 3, 1, 5, 6, 8])
g.data("Peaches", [9, 9, 10, 8, 7, 9])

g.labels = {0 => '2003', 2 => '2004', 4 => '2005'}

g.write('my_fruity_graph.png')

Note: I executed the code within an irb session on my Gentoo box. With Gentoo, Gruff was installed [gentoo-portage.com] using the command emerge -va gruff. I tried installing it on Ubuntu but ran into some difficulty, even with help from the article install rmagick ubuntu [dzone.com].

*udpate 21:48 24-Feb*

The following code does exactly as the same code above, however it uses XML to separate the data from the process, making it easier and more efficient to build graphs.

#!/usr/bin/ruby
# file: xml2gruff.rb

require 'rexml/document'
require 'gruff'
include REXML

class Xml2Gruff

def initialize(filename)
file = File.new(filename, 'r')
doc = Document.new(file)
# get the title
@title = doc.root.elements['summary/title'].text

@record = Hash.new
# get each record
doc.root.elements.each('records/item') {|item|
avalues = Array.new
item.elements.each('values/value') { |value| avalues

Read »
Created by BSOD Created 38 weeks 3 days ago
Category: Programming   Tags: