Konrad Viltersten Konrad Viltersten - 1 year ago 77
Javascript Question

Can't create non-overlapping sectors in D3 while drawing the arcs

While drawing a pie chart, my sectors are overlapping. When I hover with the finder tool, I can see that each sector starts at zero (while it should start at the ending angle of the previous element). Also, it seems that the size of the sectors is cumulative (data of 1, 2, 4 gives me sectors of weight 1, 3, 7). I've got it in a fiddle here.

var height = 400, width = 600, radius = Math.min(height, width) / 2;
var colors = ["red", "pink", "green", "yellow",
var data = [1,2,1,2,1,2,1,3,1];

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

var pie = d3.layout.pie().sort(null).value(function (d) { return d; });
var arc = d3.svg.arc().startAngle(0).innerRadius(0).outerRadius(radius);

var grx = chart.selectAll(".sector").data(pie(data))
.enter().append("g").attr("class", "sector");

.attr("d", arc)
.style("fill", function (d, i) {
return colors[i];

Answer Source

You're setting the starting angle to zero at each data point. It gets recomputed and spans over the angle of zero-to-whatever. If you don't assign the starting angle, it's going to be by default set to the previous element's ending angle.

var pie = d3.layout.pie().sort(null).value(function (d) { return d; });
var arc = d3.svg.arc().innerRadius(0).outerRadius(radius);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download