D3 Examples

Richard Dalton

Bar Chart

We can draw a bar chart by usig svg to render a rectangle of the appropriate size for each datapoint.

In this example, we also use a D3 logarithmic scale, to map the domain of values 5-1300 to the range of bar heights 0-500.

    var w = 500;
    var h = 500;
    var barPadding = 1;

    var dataset = [ 5, 10, 100, 279, 500, 25, 750, 1200, 800, 1300,
        110, 102, 15, 200, 175, 168, 180, 230, 205 ];

    var scale = d3.scale.log();
    scale.domain([5, 1300]);
    scale.range([0, 500]);

    var svg = d3.select("#draw_here")
            .append("svg")
            .attr("width", w)
            .attr("height", h);

    svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("x", function(d, i) {
                return i * (w / dataset.length);
            })
            .attr("y", function(d) {
                return h - scale(d);
            })
            .attr("width", w / dataset.length - barPadding)
            .attr("height", function(d) {
                return scale(d);
            })
            .attr("fill", function(d) {
                return "rgb(0, 0, " + (d * 10) + ")";
            });

    svg.selectAll("text")
            .data(dataset)
            .enter()
            .append("text")
            .text(function(d) {
                return d;
            })
            .attr("text-anchor", "middle")
            .attr("x", function(d, i) {
                return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2;
            })
            .attr("y", function(d) {
                return h - scale(d) + 14;
            })
            .attr("font-family", "sans-serif")
            .attr("font-size", "11px")
            .attr("fill", "white");