筛选路径并追加文本



我想在路径上设置过滤器并附加文本,但没有任何反应。

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.

绑定数据将传递给子文本,允许您在添加子文本之前筛选父项选择。

另一种方法更接近您已经完成的操作,但您没有惯用的 d3。我们也不需要将数据重新绑定到路径(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")

顺便说一句,您最初的方法是有问题的,因为它:

  • 它直接将文本附加到路径元素,这不会呈现(如您所注意的)
  • 它再次将数据绑定到路径,对于选择中的每个元素,您将数据数组的一个项目绑定到所选元素 - 由于选择是路径的子集,但您的数据是完整的数据集,因此您可能会为每个路径分配不同的数据(不指定标识符, 完整数据集中的第i项绑定到子选择中的第i个元素)。

我想我现在有一个解决方案。我的文本节点位于我的路径节点内。现在我只是在我的 if 条件下执行此操作,并将我的文本节点添加到我的路径下。

svgContainer.selectAll("path")
.data(feat.features)
.filter(function (d) {
if (d.properties.myID > 0) {
d3.select("svg")
.append("text")
.attr("x", path.centroid(d)[0])
.attr("y", path.centroid(d)[1])
.attr("text-anchor", "middle")
.attr("font-size", "2px")
.text("foo")
};
})

最新更新