Recently, I faced the problem of using charts in Grails web-application. At first, I was thinking about using well-known java libraries, such as JFreeChart. JFreeChart has a nice look, nice written documentation, and pretty simple to use.
But I was wondering about any Grails plugins that may be a better fit to the needs of our web-application. And the first plug-in I found, seemed to be pretty popular, it was a Google Chart Plugin , but what i didn’t found, was a good documentation. Actually, the thing this plugin do is build an URL that leads to the chart, generated by google chart service. So if its fine with you to use other external web service in your application you could use Google Char API. And if its not, you should probably use java library, or JFreeChart Eastwood plug-in for Grails , that uses JFreeChart for emulating look of Google charts.
But the more simple and fast way to build a chart is actually using the Google Chart API . The way it works is downloading AJAX API and visualization library, then it process received data and build the chart within the browser using SVG or VML.
It has a lot of different types of charts, pretty flexible and easy to customize. The only reason why I can’t say that this is the best solution to use in charts of web-application is the need of downloading API and library every time the page loads, so it may slow down the work of the web-application on a really slow connections.
Eventually I decided to use Google Chart API, and here is some code, which draws an area chart with a date showing on the horizontal axis, it shows how simple it is to draw a charts with this tool.
<script type='text/javascript'>
// Load the Visualization API and the area chart package.
google.load('visualization', '1', {packages:['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the area chart, passes in the data and
// draws it.
function drawChart() {
//Creates data table with the data passed from the Grails controller.
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Subscribers');
//List of the values to show.
var subs = ${subscribers};
//Start date of chart's horizontal axis.
var date = new Date(${currentMonthDate.year + 1900}, ${currentMonthDate.month}, ${currentMonthDate.date});
for (var i = 0; i < subs.length; i++) {
data.addRow([new Date(date.getTime() + i * 86400000), subs[i]])
}
//Instantiate and draw a chart to the 'chart_div' div.
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 300, backgroundColor: '#ffffff', legend: 'top'});
}
</script>
Code language: HTML, XML (xml)