This tutorial explains one of the leading charting library FusionCharts and how to create a column chart using the FusionCharts.
Understanding and analyzing data in the form of numbers is always difficult. But when the same is represented visually things become easier to understand and make sense very quickly. Ìn this post I am going to show you how to represent data in the form of charts.
The sample data I am going to use is that of the top 10 run scorers in ODI Cricket in the year 2015. The same data can be found on cricinfo here.
For building the charts there are lot of options available both client side and server side charts. But in this post I am going to make use of a popular Javascript API FusionCharts.
What is FusionCharts?
As per their official documentation, a FusionCharts is:
FusionCharts is an open-source FREE flash charting component that can be used to render data-driven animated charts. Made in Macromedia Flash MX, FusionCharts can be used with any web scripting language like PHP, ASP, .NET, JSP, ColdFusion, JavaScript, Ruby on Rails etc., to deliver interactive and powerful charts. Using XML as its data interface, FusionCharts makes full use of fluid beauty of Flash to create compact, interactive and visually-arresting charts.
The post is going to consists of following parts:
- Building Node.js backend for fetching data
- Interacting with the Node.js backend from Javascript client
- Rendering the chart using the data obtained
Building Node.js backend for fetching data
- You might like to read : Node.js and MongoDB Performing CRUD Operations
First let us import the below data into mongodb collection:
[ {"player": "AB de Villiers", "runs":162}, {"player": "CH Gayle", "runs":215}, {"player": "KJ Coetzer", "runs":156}, {"player": "L Ronchi", "runs":170}, {"player": "TM Dilshan", "runs":161}, {"player": "MJ Guptil", "runs":237}, {"player": "HM Amla", "runs":153}, {"player": "AB de Villiers", "runs":149}, {"player": "HM Amla", "runs":159}, {"player": "DA Warner", "runs":178} ]Save the above JSON into a file name data.json and then use the following command to import the above data:
mongoimport -d test -c top_scores --type json --file data.json --jsonArrayWith this we now have the data in our mongodb and the same can be confirmed by running the following command:
> db.top_scores.find(); { "_id" : ObjectId("55be11f845ed173efcfc34d4"), "player" : "AB de Villiers", "runs" : 162 } { "_id" : ObjectId("55be11f845ed173efcfc34d5"), "player" : "CH Gayle", "runs" : 215 } { "_id" : ObjectId("55be11f845ed173efcfc34d6"), "player" : "KJ Coetzer", "runs" : 156 } { "_id" : ObjectId("55be11f845ed173efcfc34d7"), "player" : "L Ronchi", "runs" : 170 } { "_id" : ObjectId("55be11f845ed173efcfc34d8"), "player" : "TM Dilshan", "runs" : 161 } { "_id" : ObjectId("55be11f845ed173efcfc34d9"), "player" : "MJ Guptil", "runs" : 237 } { "_id" : ObjectId("55be11f845ed173efcfc34da"), "player" : "HM Amla", "runs" : 153 } { "_id" : ObjectId("55be11f845ed173efcfc34db"), "player" : "AB de Villiers", "runs" : 149 } { "_id" : ObjectId("55be11f845ed173efcfc34dc"), "player" : "HM Amla", "runs" : 159 } { "_id" : ObjectId("55be11f845ed173efcfc34dd"), "player" : "DA Warner", "runs" : 178 }Now let us write a Node.js based web server using Express to fetch data from the MongoDB and return it in the form:
[{"label":"MJ Guptil", "value": 237}, ...]The above structure of data is what processed by FusionCharts API.
The below is the code for the Node.js server:
//Express is required for creating Node.js based web apps var express = require('express'); //Importing the required mongodb driver var MongoClient = require('mongodb').MongoClient; //MongoDB connection URL var dbHost = 'mongodb://localhost:27017/test'; //Name of the collection var myCollection = "top_scores"; //DB Object var dbObject; //Connecting to the Mongodb instance. //Make sure your mongodb daemon mongod is running on port 27017 on localhost MongoClient.connect(dbHost, function(err, db){ if ( err ) throw err; dbObject = db; }); var app = express(); app.set('port', 3300); //Starting up the server on the port: 3300 app.listen(app.get('port'), function(){ console.log('Server up: http://localhost:' + app.get('port')); }); app.get("/scores", function(req, res){ //Query Mongodb and iterate through the results dbObject.collection(myCollection).find({},{},{}).toArray( function(err, docs){ var result = []; for(index in docs){ var doc = docs[index]; var resultObject = {}; resultObject.label = doc.player; resultObject.value = doc.runs; result.push(resultObject); } res.json(result); } ); });Save the above code in the file and name it as:
column_chart_sample_server.js
. Run the above code by using the following command:G:\node\testapp>node column_chart_sample_server.js Server up: http://localhost:3300This will run the server on port 3300. Open your browser and load the URL: http://localhost:3300/scores. You would see the response of the API.
Interacting with the Node.js backend from Javascript client
- also read: Introduction to Node.js
Now let us invoke the above API from Javascript and for that I would use jQuery as shown below:
$(function(){ $.ajax({ url: 'http://localhost:3300/scores', type: 'GET', crossDomain: true, success : function(data) { console.log(data); } }); });Rendering the FusionCharts using the data obtained
As mentioned at the beginning of the post I would be using FusionCharts Javascript library for rendering column chart. Firstly, Download the following:
- Required Javascript code for FusionCharts from here.
- Bootstrap CSS library from here. I will use it for any CSS related requirements.
- Latest jQuery code from here.
After downloading all the relevant sources, copy the files from their corresponding locations and build a directory structure as shown in the image below:
In the above image there are two files namely: column_chart_sample.html
and column_chart_sample.js
. I would be implementing these two files in this post. column_chart_sample.html
contains the required HTML code and column_chart_sample.js
contains the code for invoking the server API and initializing the FusionCharts code.
The below is the code for column_chart_sample.html
:
<!DOCTYPE html> <html> <head> <title>Sample for Column Chart using FusionChart</title> <link rel="stylesheet" href="css/bootstrap.css"/> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <h3>Top 10 run scorers in ODI cricket in the year 2015</h3> <!-- Container for rendering the chart --> <div id="chart-container"></div> </div> </div> </div> <!-- jQuery Javascript --> <script src="js/jquery-2.1.4.js"></script> <script src="js/bootstrap.js"></script> <!-- FusionCharts related Javascript library --> <script src="js/fusioncharts.js"></script> <script src="js/fusioncharts.charts.js"></script> <script src="js/fusioncharts.theme.zune.js"></script> <script src="js/column_chart_sample.js"></script> </body> </html>Let us know step by step build the Javascript code for rendering the chart.
- Create a JSON object of chart properties:
var chartProperties = { "caption": "Top 10 run scorers in ODI Cricket in 2015", "xAxisName": "Player", "yAxisName": "Runs Scored", "rotatevalues": "1", "theme": "zune" };- Get the data for the chart by invoking the Server side API created at the beginning as shown below:
var chartData; $(function(){ $.ajax({ url: 'http://localhost:3300/scores', type: 'GET', crossDomain: true, success : function(data) { chartData = data; } }); });- Creating an instance of FusionCharts by passing the id of the HTML element where the chart would be rendered, dimensions of the chart, type of the chart, data format and data source of the chart as shown below:
var apiChart = new FusionCharts({ type: 'column2d', renderAt: 'chart-container', width: '550', height: '350', dataFormat: 'json', dataSource: { "chart": chartProperties, "data": chartData } });We have already seen how
chartProperties
andchartData
object is built.- Render the chart using the below code:
apiChart.render();Putting all together the
column_chart_sample.js
looks like below:var chartData; $(function(){ $.ajax({ url: 'http://localhost:3300/scores', type: 'GET', crossDomain: true, success : function(data) { chartData = data; var chartProperties = { "caption": "Top 10 run scorers in ODI Cricket in 2015", "xAxisName": "Player", "yAxisName": "Runs Scored", "rotatevalues": "1", "theme": "zune" }; var apiChart = new FusionCharts({ type: 'column2d', renderAt: 'chart-container', width: '550', height: '350', dataFormat: 'json', dataSource: { "chart": chartProperties, "data": chartData } }); apiChart.render(); } }); });To run this example on Chrome, follow the steps below:
- Install the Allow-Control-Allow-Origin: * plugin from Chrome Webstore.
- Load the column_chart_sample.html in the Chrome browser
OR
Copy the entire project folder to an Apache Webserver www folder and load the following URL in the browser: http://localhost:8080/fusioncharts/column_chart_sample.htmlOn other browsers you would see an error message similar to: “CORS header ‘Access-Control-Allow-Origin’ missing“.
Once you have loaded the HTML you would see a chart rendered as shown below:
With this I have shown you how to load the data from a DB and represent it in the form of a column chart to the end user.