javascript 防止 D3 饼图中的文本重叠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14534024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:53:42  来源:igfitidea点击:

Preventing overlap of text in D3 pie chart

javascriptd3.jslabelpie-chartoverlap

提问by user1431282

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 D3and 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?

我是一个完全的初学者,D3并试图防止文本重叠。有没有像我可以添加的文本边距属性,这样我的标签就不会相互重叠?

回答by musically_ut

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

更新如果有足够的空间来提供更全面的解决方案,请参阅D3 put arc labels in a Pie Chart的答案。



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/

但是,通过旋转标签和缩放图形使它们不重叠,可以解决您的问题: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; });

回答by jamesRH

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/

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.

Musically_ut 的解决方案在这里也能很好地工作。如果这在您的设计中有效,您甚至可以将角度降低一点。

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

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

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.

您需要创建一个 if else 块来处理 USA 项目,但如果有帮助,这是一个开始。