我使用d3 chord图示例安德鲁,并希望将所有文本标签集中在曲线切片中。我尝试了许多事情,但始终无法集中文字。你知道需要什么奇才术吗?

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>发布于 2017-06-09 01:28:39
顺便提一下,我建议升级到v4,v2的文档几乎不存在,而且很难帮助。
您可以同时设置text-anchor和startOffset属性以实现所需的功能。
首先,您需要将text-anchor设置为middle,因为指定中间点要比找到中间点要容易,并且返回到文本应该从哪里开始。
其次,您需要设置一个startOffset。请注意,如果您使用50%,文本将不会出现在您想要的地方,因为文本路径的总长度是所附加的闭环(chord锚)的所有侧面。如果你没有不同的外径和内半径,那么将其设置为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)。
这是最终结果:

这里是一个演示。
https://stackoverflow.com/questions/44447188
复制相似问题