donut_basic.js 2.42 KB
Newer Older
Felipe Escala Torres committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
/* ------------------------------------------------------------------------------
 *
 *  # D3.js - basic donut chart
 *
 *  Demo d3.js donut chart setup with .csv data source
 *
 *  Version: 1.0
 *  Latest update: August 1, 2015
 *
 * ---------------------------------------------------------------------------- */

$(function () {

    // Initialize chart
    donutBasic('#d3-donut-basic', 120);

    // Chart setup
    function donutBasic(element, radius) {


        // Basic setup
        // ------------------------------

        // Colors
        var color = d3.scale.category20();


        // Create chart
        // ------------------------------

        // Add SVG element
        var container = d3.select(element).append("svg");

        // Add SVG group
        var svg = container
            .attr("width", radius * 2)
            .attr("height", radius * 2)
            .append("g")
                .attr("transform", "translate(" + radius + "," + radius + ")");


        // Construct chart layout
        // ------------------------------

        // Arc
        var arc = d3.svg.arc()
            .outerRadius(radius)
            .innerRadius(radius / 1.75);

        // Pie
        var pie = d3.layout.pie()
            .sort(null)
            .value(function(d) { return d.population; });


        // Load data
        // ------------------------------

        d3.csv("assets/demo_data/d3/pies/pies_basic.csv", function(error, data) {

            // Pull out values
            data.forEach(function(d) {
                d.population = +d.population;
            });


            //
            // Append chart elements
            //

            // Bind data
            var g = svg.selectAll(".d3-arc")
                .data(pie(data))
                .enter()
                .append("g")
                    .attr("class", "d3-arc");

            // Add arc path
            g.append("path")
                .attr("d", arc)
                .style("stroke", "#fff")
                .style("fill", function(d) { return color(d.data.age); });

            // Add text labels
            g.append("text")
                .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
                .attr("dy", ".35em")
                .style("fill", "#fff")
                .style("font-size", 12)
                .style("text-anchor", "middle")
                .text(function(d) { return d.data.age; });
        });
    }
});