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},
              {name:"B",value:5},
              {name:"C",value:2}];
var margin = {top: 20, right: 20, bottom: 40, left: 40};
var width = 400;
var height = 300;
var x = d3.scale.ordinal()
    .domain(myData.map(function(d){ return d.name; }))
    .rangeRoundBands([margin.left, width-margin.right], 0.1);
var y = d3.scale.linear()
    .domain([0, d3.max(myData, function(d){ return d.value; })])
    .range([height-margin.bottom, margin.top]);
var h = d3.scale.linear()
    .domain([0, d3.max(myData, function(d){ return d.value; })])
    .range([0, height-margin.top-margin.bottom]);
var xAxis = d3.svg.axis()
    .scale(x);
var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5);
var svg = d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height);
svg.append("g")
    .attr('class', 'axis')
    .attr("transform", "translate(0,"+(height-margin.bottom)+")")
    .call(xAxis);
svg.append("g")
    .attr('class', 'axis')
    .attr("transform", "translate("+margin.left+",0)")
    .call(yAxis);
var bar = svg.selectAll('.data').append('rect')
    .data(myData);
bar.enter().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