我想在路径上设置过滤器并附加文本,但没有任何反应。
var filteredElements = svgContainer.selectAll("path")
//.data(feat.features)
.append("text")
.filter(function (d) {
if (d.properties.myID > 0) {
return true;
};
})
.attr("x", function (d) {
return path.centroid(d)[0];
})
.attr("y", function (d) {
return path.centroid(d)[1];
})
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo");
filteredElements 包含 46 个正确但未附加文本的元素。
使用该代码,它可以正常工作,但我需要过滤器中的条件:
svgContainer.selectAll("path[PE='1442']")
.data(feat.features)
.enter().append("text")
.attr("x", function (d) {
return path.centroid(d)[0];
})
.attr("y", function (d) {
return path.centroid(d)[1];
})
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo");
最佳答案
我将其添加为第二个答案,因为评论中没有足够的空间,但它本身就足以作为答案。
您在 svg 上绘制了路径,并且您想要为这些路径的子集绘制文本。
有两种方法可用于此目的。一种是使用父 g
元素来保存路径和文本:
// Append a parent:
var g = svg.selectAll(null) // we want to enter an element for each item in the data array
.data(features)
.enter()
.append("g");
// Append the path
g.append("path")
.attr("d",path)
.attr("fill", function(d) { ... // etc.
// Append the text to a subset of the features:
g.filter(function(d) {
return d.properties.myID > 0; // filter based on the datum
})
.append("text")
.text(function(d) { .... // etc.
绑定(bind)数据被传递给 child ,允许您在添加子文本之前过滤父选择。
另一种方法更接近于您已经完成的方法,但您并不完全具备惯用的 d3。我们也不需要将数据重新绑定(bind)到路径 (d3.selectAll("path").data(
),我们可以使用:
svgContainer.selectAll(null)
.data(feat.features.filter(function(d) { return d.properties.myID > 0; }))
.enter()
.append("text")
.attr("x", path.centroid(d)[0])
.attr("y", path.centroid(d)[1])
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo")
顺便说一句,您最初的方法存在问题,因为它:
- 它直接将文本附加到路径元素,不会呈现(正如您所注意到的)
- 它再次将数据绑定(bind)到路径,对于选择中的每个元素,您将数据数组的一个项目绑定(bind)到所选元素 - 因为选择是您路径的子集,但您的数据是完整数据集,您可能会为每个路径分配不同的数据(在不指定标识符的情况下,完整数据集中的第
i
项绑定(bind)到子中的第i
元素-选择)。
关于javascript - 过滤路径并附加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55354431/