Xiaopei's DokuWiki

These are the good times in your life,
so put on a smile and it'll be alright

User Tools

Site Tools


it:javascript:d3

d3.js - data-driven documents

examples

histogram 柱状图

var width = 900,
    height = 300,
    pad = 20, 
    left_pad = 100;
 
// range 是按绝对起止坐标计算
var x = d3.scale.ordinal().rangeRoundBands([left_pad, width-pad], 0.1);
var y = d3.scale.linear().range([height-pad, pad]);
 
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
 
var svg = d3.select("#graph")
        .append("svg")
        .attr("width", width)
        .attr("height", height);
 
d3.json('histogram-hours.json', function (data) {
    /*
      { "0": 5529632,
        "1": 4431841,
        // ...
        "23": 6750381 }
    */
    data = d3.keys(data).map(function (key) {
        return {bucket: Number(key),
                N: data[key]};
    });
 
    x.domain(data.map(function (d) { return d.bucket; }));
    y.domain([0, d3.max(data, function (d) { return d.N; })]);
 
    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0, "+(height-pad)+")")
        .call(xAxis);
 
    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate("+(left_pad-pad)+", 0)")
        .call(yAxis);
 
    svg.selectAll('rect')
        .data(data)
        .enter()
        .append('rect')
        .attr('class', 'bar')
        .attr('x', function (d) { return x(d.bucket); })
        .attr('width', x.rangeBand())
        .attr('y', height-pad)
        .transition()
        .delay(function (d) { return d.bucket*20; })
        .duration(800)
        .attr('y', function (d) { return y(d.N); })
        .attr('height', function (d) { return height-pad - y(d.N); });
 
});
it/javascript/d3.txt · Last modified: 2014/07/06 20:37 by admin