如何向 d3 生成的凸包添加标签?

How do I add a label to a d3-generated convex hull?

我使用了 d3 v4 和 this technique (slightly modified) to draw a convex hull around nodes in a force-directed graph. Works great, but now I want to label these groups of nodes. Ultimately, I'd like to draw something that looks like this SVG。是否可以将文本元素添加到凸空多边形,以便它随着多边形的移动而四处移动,或者我是否需要创建某种单独的分组?

我会这样处理问题:

  • 从点创建凸包多边形
  • 使用 d3.geom 或 d3.polygon(取决于版本)找到该多边形的质心
  • 用中心的新坐标更新一些文本

在 d3 v4 中,这类似于:

var polygon = d3.polygonHull(vertices); 

然后你找到质心:

var centroid = d3.polygonCentroid(polygon);

并更新文本:

text.attr("transform","translate("+ centroid +")")

在 d3v3 和 v2 中,代码可能看起来更像:

var polygon = d3.geom.polygon(d3.geom.hull(vertices));
var centroid = polygon.centroid();
text.attr("transform","translate("+centroid+")");

至于一次更新多个文本,有很多潜在的方法可以实现,所以我不会在这里讲。

这是在 v4 中更新的 single text 元素的示例。