Thursday, September 19, 2013

D3 - Build chart so easy

Today I would like to introduce an interesting library, D3. D3 means "Data Driven Document", which is a javascript data visualization library. With this library, you can very easy to repersent data in a more fancy way. Here are some offical examples.
D3 strong at make use of HTML5 inline SVG to render graphic, so it is not compatible with IE8. Eventhough there is such a limitation, I found that D3 is so easy to use, with great support for animation and interaction, and its key concept of data driven is really good at ploting graph.
The following is an example of a very simple bar chart. Note that since D3 is not a plugin but it is a library, I think use 40 lines code to build a bar chart is pretty good.

var myData = [{name:"A",value:3},
var margin = {top: 20, right: 20, bottom: 40, left: 40};
var width = 400;
var height = 300;
var x = d3.scale.ordinal()
    .domain({ return; }))
    .rangeRoundBands([margin.left, width-margin.right], 0.1);
var y = d3.scale.linear()
    .domain([0, d3.max(myData, function(d){ return d.value; })])
var h = d3.scale.linear()
    .domain([0, d3.max(myData, function(d){ return d.value; })])
var xAxis = d3.svg.axis()
var yAxis = d3.svg.axis()
var svg ='body').append('svg')
    .attr('width', width)
    .attr('height', height);
    .attr('class', 'axis')
    .attr("transform", "translate(0,"+(height-margin.bottom)+")")
    .attr('class', 'axis')
    .attr("transform", "translate("+margin.left+",0)")
var bar = svg.selectAll('.data').append('rect')
    .attr('class', 'data')
    .attr("width", x.rangeBand())
    .attr("height", function(d){ return h(d.value); })
    .attr('x', function(d){ return x(d.value); })
    .attr('y', function(d){ return y(d.value); });

Live Demo Here
In the next blog post, I'll dig in to the D3 and explian how to use.

No comments:

Post a Comment