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 (u.id = ech.to)
    LEFT JOIN user_contact uc ON (uc.user_id = u.id)
    LEFT JOIN city cty ON (cty.id = uc.city_id)
    LEFT JOIN country cntry ON (cntry.id = cty.country_id)    
    WHERE ech.transaction = 0 AND ech.date >= ? AND ech.date <= ?    
    GROUP BY cntry.id
    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();
while(rs.next()){
 // Here goes charts for country
 JSONObject chartJSON   = new JSONObject();
 ArrayList<Integer> chartValues  = new ArrayList<Integer>();
 chartValues.add(rs.getInt("ecard_count"));
 chartJSON.put("label", rs.getString("abbreviation"));
 chartJSON.put("values", chartValues); 
    
 values.add(chartJSON);
}  
  
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: {  
     top:5,  
     left: 5,  
     right: 5,  
     bottom:5  
   },  
   //labels offset position  
   labelOffset: 5,  
   //bars style  
   type: useGradients? 'stacked:gradient' : 'stacked',  
   //whether to show the aggregation of the values  
   showAggregates:true,  
   //whether to show the labels for the bars  
   showLabels:true,  
   //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.name + ": " + elem.value;  
     }  
   }  
 });  
 
 //load JSON data.  
 barChart.loadJSON(json);
}
Call your function from jsp page and pass JSON string which we generated above.

No comments:

Post a Comment