Friday, August 26, 2011

Pure Javascript Bar chart

To show a chart, an existing library for charts creation will be necessary. I have chosen to use The jit Javascript library. In this library u create JSON object in server side then call your javascript function with JSON string parameter in user side. This is pure javascript library.

I choose this library because when  I search library for my genealogy tree I have found this lib more useful. For example I have created one diagram yesterday, which must show purchased ecards count by country.

So my SQL looks like following:

SELECT cntry.*, COUNT(ech.ecard_id) ecard_count FROM ecard_history ech
    LEFT JOIN users u ON ( =
    LEFT JOIN user_contact uc ON (uc.user_id =
    LEFT JOIN city cty ON ( = uc.city_id)
    LEFT JOIN country cntry ON ( = cty.country_id)    
    WHERE ech.transaction = 0 AND >= ? AND <= ?    
    ORDER BY cntry.title;
Generation JSON object:
JSONObject json = new JSONObject();
ArrayList<String> labels = new ArrayList<String>();
ArrayList<JSONObject> values = new ArrayList<JSONObject>();
labels.add("Purchased Ecards");
rs = prepStmnt.executeQuery();
 // Here goes charts for country
 JSONObject chartJSON   = new JSONObject();
 ArrayList<Integer> chartValues  = new ArrayList<Integer>();
 chartJSON.put("label", rs.getString("abbreviation"));
 chartJSON.put("values", chartValues); 
json.put("label", labels);
json.put("values", values);
Your Javascript code goes here:
function showDiagram(jsonStr){

 var json = eval('(' + jsonStr + ')');
 var barChart = new $jit.BarChart({  
   //id of the visualization container  
   injectInto: 'infovis',  
   //whether to add animations  
   animate: true,  
   //horizontal or vertical barcharts  
   orientation: 'vertical',  
   //bars separation  
   barsOffset: 20,  
   //visualization offset  
   Margin: {  
     left: 5,  
     right: 5,  
   //labels offset position  
   labelOffset: 5,  
   //bars style  
   type: useGradients? 'stacked:gradient' : 'stacked',  
   //whether to show the aggregation of the values  
   //whether to show the labels for the bars  
   //labels style  
   Label: {  
     type: labelType, //Native or HTML  
     size: 13,  
     family: 'Arial',  
     color: 'Black'  
   //add tooltips  
   Tips: {  
     enable: true,  
     onShow: function(tip, elem) {  
       tip.innerHTML = "" + + ": " + elem.value;  
 //load JSON data.  
Call your function from jsp page and pass JSON string which we generated above.

No comments:

Post a Comment