Thursday, July 24, 2014

My First Try with D3.js

I have to say D3.js is such an amazing library. Although I just started a few days ago, I have already get a pretty good idea how it works. Anyway, I started with simple bar plot and here is what I got - DEMO.

It is a simple bar plot with color intensity to indicate their values. Once the update button is clicked, it will generate a batch of new data and assign them to the plot. A transition is used during the update.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 First Demo</title>
        <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
        <style>
         rect:hover { fill: orange; }
        </style>
    </head>
    <body>
     <svg class="my">test</svg>
     <br />
     <button class="control">Update</button>
        <script type="text/javascript">
            // data
            var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
            // plot parameters
            var w = 480;
            var h = 200;
            // x, y scale
            var xScale = d3.scale.ordinal()
                .domain(d3.range(dataset.length))
                .rangeRoundBands([0, w], 0.2);
            var yScale = d3.scale.linear()
                .domain([0, d3.max(dataset)])
                .range([0, h]);
            // get svg
            var svg = d3.select(".my")
               .attr("width", w)
               .attr("height", h);
            svg.selectAll(".bar")
             .data(dataset)
             .enter()
             .append("rect")
             .attr("x", function(d,i) { return xScale(i); })
             .attr("y", function(d) { return yScale(d3.max(dataset)-d); })
             .attr("width", xScale.rangeBand())
             .attr("height", function(d) { return yScale(d); })
             .attr("fill", function(d) { return "rgba("+Math.floor(yScale(d))+",30,30,0.7)"; });
            // control
            d3.select(".control").on("click", function(){
             update();
             // debug
             console.debug("Click detected");
            });
            function dataGenerate () {
             dataset = [];
          for (var k=0; k<20; k++) {
           dataset.push(Math.floor(((Math.random()+0.5)*20)));
          }
         }
         function update () {
          dataGenerate();
             svg.selectAll("rect")
              .data(dataset)
              .attr("fill", function(d) { return "rgba("+Math.floor(yScale(d))+",30,30,0.7)"; })
              .transition()
              .duration(1000)
              .attr("y", function(d) { return yScale(d3.max(dataset)-d); })
              .attr("height", function(d) { return yScale(d); });
         }
        </script>
    </body>
</html>

No comments:

Post a Comment