Preventing overlap of text in D3 pie chart

那年仲夏 提交于 2019-11-29 10:15:47
musically_ut

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!