Preventing overlap of text in D3 pie chart

安稳与你 提交于 2019-11-28 03:36:20

问题


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

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?


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



回答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.



来源:https://stackoverflow.com/questions/14534024/preventing-overlap-of-text-in-d3-pie-chart

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