Easy Charts in FXRuby with the Google Chart API

InfoQ has just published an article written by Matthew Bass that introduces the Google Chart API and the gchartrb library, which you can use to programmatically generate URLs for use with Google Chart. It’s very easy to use this library to generate charts in your FXRuby applications. First, install the gchartrb gem:

$ sudo gem install gchartrb
You’ll need to poke around the gchartrb documentation to decide just what kinds of charts are supported; for this example, we’ll just use a bar chart example from Matthew’s article:

def bar_chart
  GoogleChart::BarChart.new('600x200', 'My Chart', :vertical) do |bc|
    bc.data 'Trend 1', [5,4,3,1,3,5], '0000ff'
    bc.data 'Trend 2', [1,2,3,4,5,6], 'ff0000'
    bc.data 'Trend 3', [6,5,4,4,5,6], '00ff00'
  end
end

The toescapedurl method for the BarChart object returns a URL from which we can retrieve the chart image data in PNG format. We can in turn use that data to construct an FXPNGImage, and place it inside an FXImageFrame:

FXImageFrame.new(self, nil, :opts => LAYOUT_FILL) do |f|
  f.image = FXPNGImage.new(app, open(bar_chart.to_escaped_url, "rb").read)
end

The result is a nice little bar chart, as shown here:

google_charts_demo.png

For reference, here’s the complete program:

Posted June 5th, 2008 in FXRuby, Ruby. Tagged: , , , , .

One comment:

  1. kenneth:

    Sweet, using it on my app. Cool stuff! Roby rocks.