Preventing overlap of text in D3 pie chart

user1431282 picture user1431282 · Jan 26, 2013 · Viewed 11.4k times · Source

I've been googling around, but I can't seem to grasp this.

My situation is that the countries overlap when presented on the pie chart:

This is an example of what is happening:

jsfiddle

enter image description here

I am a total beginner to D3 and am trying to prevent text overlap. Is there like a text margin attribute that I can add such that my labels don't overlap each other?

Answer

musically_ut picture musically_ut · Jan 26, 2013

Update: See the answer to D3 put arc labels in a Pie Chart if there is enough space for a more comprehensive solution.


I do not know any generic method of laying text elements such that they do not overlap.

However, there is a workaround for your problem by rotating the labels and scaling the graph such that they do not overlap: http://jsfiddle.net/2uT7F/

// Get the angle on the arc and then rotate by -90 degrees
var getAngle = function (d) {
    return (180 / Math.PI * (d.startAngle + d.endAngle) / 2 - 90);
};

g.append("text")
    .attr("transform", function(d) { 
            return "translate(" + pos.centroid(d) + ") " +
                    "rotate(" + getAngle(d) + ")"; }) 
    .attr("dy", 5) 
    .style("text-anchor", "start")
    .text(function(d) { return d.data.label; });