Preventing overlap of text in D3 pie chart

12,344

Solution 1

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; });

Solution 2

One more solution would be to change the order of the data with the USA being first. You might find the angle of the pie layout to be more readable.

var data_values = [48, 1, 1, 1, 1, 1, 1, 4];
var titles = ["USA","Pakistan", "Israel", "Netherlands", "Italy", "Uruguay",       "United Kingdom", "Austria", "China"]

http://jsfiddle.net/rocky1616/oLzsrd4o/

Musically_ut's solution would work nicely here as well. You can even take the angle down a bit if that worked in your design.

  var getAngle = function (d) {
      return (180 / Math.PI * (d.startAngle + d.endAngle) / 2 + 45);
  };

http://jsfiddle.net/2uT7F/26/

You would need to create a if else block to take care of the USA item but this is a start if it helps.

Share:
12,344
user1431282
Author by

user1431282

Updated on June 09, 2022

Comments

  • user1431282
    user1431282 almost 2 years

    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?