Preventing overlap of text in D3 pie chart
Asked Answered
E

2

12

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?

Extern answered 26/1, 2013 at 4:58 Comment(0)
T
12

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; });
Titration answered 26/1, 2013 at 20:2 Comment(0)
A
3

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.

Acknowledgment answered 26/1, 2015 at 1:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.