D3 Examples

Richard Dalton

Bubble Chart

We can draw a bubble chart by using svg to render a circle of the appropriate size, and at the appropriate position for each datapoint.

In this example, each data point consists of 3 numbers which we can use to plot the x and y position and the radius of each circle

    var w = 500;
    var h = 500;

    var dataset = [
        [5, 20, 5], [480, 90, 5], [250, 50, 10], [100, 33, 15], [330, 95, 5],
        [410, 12, 10], [475, 44, 20], [25, 67, 15], [85, 21, 5], [220, 88, 10]
    ];
    var colors = d3.scale.category10();

    var scaleX = d3.scale.linear();
    scaleX.domain([0, 500]);
    scaleX.range([50, 480]);

    var scaleY = d3.scale.linear();
    scaleY.domain([0, 100]);
    scaleY.range([450, 20]);


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

    svg.selectAll("circle")
            .data(dataset)
            .enter()
            .append("circle")
            .attr("cx", function (d) {
                return scaleX(d[0]);
            })
            .attr("cy", function (d) {
                return scaleY(d[1]);
            })
            .attr("r", function (d) {
                return d[2];
            })
            .attr("fill", function (d, i) {
                return colors(i);
            });

    svg.selectAll("text")
            .data(dataset)
            .enter()
            .append("text")
            .text(function (d) {
                return d[0] + "," + d[1] + "," + d[2];
            })
            .attr("x", function (d) {
                return scaleX(d[0]);
            })
            .attr("y", function (d) {

                return scaleY(d[1]) - d[2] - 5;
            })
            .attr("font-family", "sans-serif")
            .attr("font-size", "11px")
            .attr("text-anchor", "middle");

    var xAxis = d3.svg.axis()
            .scale(scaleX)
            .orient("bottom");

    var yAxis = d3.svg.axis()
            .scale(scaleY)
            .orient("left");

    svg.append("g")
            .attr("class", "axis")
            .attr("transform", "translate(0," + (h - 50) + ")")
            .call(xAxis);

    svg.append("g")
            .attr("class", "axis")
            .attr("transform", "translate(" + 50 + ", 0)")
            .call(yAxis);