Konrad Viltersten Konrad Viltersten - 1 year ago 76
Javascript Question

Not able to center D3 pie chart

I'm trying to draw a circle with different data values as angles but for some reason, it's only the last data point that gets the color and display. I've tried to translate the svg but it seems not to budge.

I'm fairly new to D3 so I'm sure I've done something less intelligent without realizing it. As far I could tell, the angles in the g and path elements are as supposed to.

var height = 400, width = 600, radius = Math.min(height, width) / 2;
var colors = ["#red", "pink", "green", "yellow", "blue","magent","brown","olive","orange"];
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

The problem is that you're appending all the sectors of the pie to the svg node when they should be appended to the translated g node, you have two options to solve this problem

  • make chart equal to the translated g node
  • select g before all the .sectors and store that in grx

The first solution is simpler e.g.

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