1

我使用Andrew的 d3 和弦图示例,并希望将所有文本标签置于弯曲切片的中心。我尝试了很多东西,但始终无法使文本居中。你知道那里需要什么巫术技巧吗?

在此处输入图像描述

var width = 720,
height = 720,
outerRadius = Math.min(width, height) / 2 - 10,
innerRadius = outerRadius - 24;

var formatPercent = d3.format(".1%");

var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);

var layout = d3.layout.chord()
.padding(.04)
.sortSubgroups(d3.descending)
.sortChords(d3.ascending);

var path = d3.svg.chord()
.radius(innerRadius);

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "circle")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

svg.append("circle")
.attr("r", outerRadius);

d3.csv("ex_csv.csv", function(cities) {
d3.json("ex_json.json", function(matrix) {

// Compute the chord layout.
layout.matrix(matrix);

// Add a group per neighborhood.
var group = svg.selectAll(".group")
.data(layout.groups)
.enter().append("g")
.attr("class", "group")
.on("mouseover", mouseover);


// Add the group arc.
var groupPath = group.append("path")
.attr("id", function(d, i) { return "group" + i; })
.attr("d", arc)
.style("fill", function(d, i) { return cities[i].color; });

// Add a text label.
var groupText = group.append("text")
.attr("x", 6)
.attr("dy", 15);

groupText.append("textPath")
.attr("xlink:href", function(d, i) { return "#group" + i; })
.text(function(d, i) { return cities[i].name; });

// Remove the labels that don't fit. :(
groupText.filter(function(d, i) { return groupPath[0][i].getTotalLength() / 2 - 16 < this.getComputedTextLength(); })
.remove();

// Add the chords.
var chord = svg.selectAll(".chord")
.data(layout.chords)
.enter().append("path")
.attr("class", "chord")
.style("fill", function(d) { return cities[d.source.index].color; })
.attr("d", path);


}
});
});

</script>
4

1 回答 1

3

顺便说一句,我建议升级到 v4,v2 的文档几乎不存在,而且很难提供帮助。

您可以同时设置text-anchorstartOffset属性来实现您要查找的内容。

首先,您需要设置text-anchormiddle,因为指定中间点比找到中间点并返回查找文本应该从哪里开始更容易。

其次,您需要设置一个startOffset. 请注意,如果您使用 50%,文本将不会出现在您想要的位置,因为文本路径的总长度是您要附加到的闭环(和弦锚点)的所有边。如果您没有不同的外半径和内半径,将其设置为 25 % 将起作用。但是,由于您的外半径比内半径大 24 像素,您可以尝试这样的方法来计算偏移文本中心所需的像素数:

groupText.append("textPath")
.attr("xlink:href", function(d, i) { return "#group" + i; })
.text(function(d, i) { return cities[i].name; })
.attr("startOffset",function(d,i) { return (groupPath[0][i].getTotalLength() - 48) / 4 })
.style("text-anchor","middle");

我减去 48,因为锚的边是 24 个像素(半径的差异)。我除以四,因为路径本身会加倍。如果这是一条一般线,我只会除以二。

这种方法有点简单,因为每个和弦锚的外圆周和内圆周都不一样,所以我稍微偏离了一点,但它应该是可行的。

对于即将显示的标签,这会很尴尬:内半径较短,因此确定字符串是否足够短以显示的公式可能是错误的 - 这可能会导致某些字符向上爬锚点(您的示例也是 16 像素作为半径差异来计算文本是否太长,而不是 24)。

这是最终结果:

在此处输入图像描述

是一个演示。

于 2017-06-09T01:28:39.047 回答