2

I’ve succeeded in creating my first pie chart with d3 and JSON, but I’m struggling to get more than one pie chart to appear. I’ve reviewed numerous examples, including Mike Bostock’s donut-multiples, and it appears I need a for-each loop in my code.

Here’s a simplified version of my program which produces one pie chart instead of two:

<!doctype html>
<html>
<head>
    <title>Pie Chart Test</title>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>

<style>
.arc path {
    stroke: white;
}
</style>

<body>
    <script>
        var width = 300,
            height = 300,
            radius = Math.min(width, height) / 2;

        var arc = d3.svg.arc()
            .outerRadius(radius)
            .innerRadius(radius - (radius / 2));

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

        var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height)
            .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

        d3.json("data.json", function(error, data) {
            if (error) throw error;

            node = data.data[0].pie1.results;

            var g = svg.selectAll(".arc")
                .data(pie(node))
                .enter().append("g")
                .attr("class", "arc")

                g.append("path")
                    .attr("d", arc)
                    .style("fill", function(d) { 
                        if (d.data.failures > 0) {
                            return "#d63535";
                        } else {
                            return "#22c12d";
                        }
                    });
        });
    </script>
</body>
</html>

and here is the JSON that populates the chart:

    {"data":[
    {"pie1": {
        "results": [
            {"ratio": 0.04, "total": 7, "failures": 1},
            {"ratio": 0.04, "total": 8, "failures": 0},
            {"ratio": 0.04, "total": 9001, "failures": 0}
        ]}
    },
    {"pie2": {
        "results": [
            {"ratio": 0.04, "total": 10, "failures": 0},
            {"ratio": 0.04, "total": 11, "failures": 1},
            {"ratio": 0.04, "total": 12, "failures": 1}
        ]}
    }
]}