Friday, May 14, 2010

Generating Graphs with JFreeChart

jRuby gives us access to all the libraries available for the Java platform; I have recently started looking at JFreeChart, which seems capable of generating all kinds of fancy graphs, with very little work. To write programs using JFreeChart you need to download the software, and extract the jar files: jcommon-X.jar and jfreechart-X.jar (where the -X stands for the version numbers). I tend to rename the jar files to jcommon.jar and jfreechart.jar.

Examples of using JFreeChart are available in different places: there are examples within the source code (in the folder source/org/jfree/chart/demos/), and an
article at InformIT from 2004 to help guide you into the APIs. Some examples are coming up for other scripting languages on the java platform, such as this example using Groovy to plot a simple piechart. Here's my own take, of a simple chart, for jRuby.

And the source code:
# jRuby implementation of simple PieChart example for JFreeChart

require "java"
require "jcommon.jar"
require "jfreechart.jar"

# -- Code to create a pie chart
include_class "org.jfree.data.general.DefaultPieDataset"
include_class "org.jfree.chart.ChartPanel"
include_class "org.jfree.chart.ChartFactory"

def create_chart
dataset = DefaultPieDataset.new
dataset.set_value("Comet Nuclei", 1.26)
dataset.set_value("Mars Asteroids", 7.0)
dataset.set_value("Apollo Objects", 0.55)

chart = ChartFactory.create_pie_chart(
"Impact Craters greater than 20km radius per million square kilometers on Mars",
dataset,
true,
true,
false
)

ChartPanel.new chart
end

# -- Code to build the Swing Frame
include_class "javax.swing.JFrame"
include_class "java.awt.BorderLayout"

def create_frame chart
frame = JFrame.new("jRuby using JFreeChart")
frame.content_pane.add(chart, BorderLayout::CENTER)
frame.setSize(600, 400)
frame.visible = true
frame.default_close_operation = JFrame::EXIT_ON_CLOSE
end

create_frame create_chart

(If you are interested, the numbers are from an article on Mariner IV and the Martian craters, by E.J. Opik.)

Finally... The fun of using JFreeChart does not end with displaying the images on the screen. A right-click on the image brings up a menu which lets you customise the image's colours, rescale, save to a file and even print. This is an enormous amount of functionality rapidly available, and the images look great.

0 comments:

Post a Comment