如何在地图标签上应用力排斥力,以便它们自动找到正确的位置?
博斯托克的《让我们制作一张地图》
迈克·博斯托克的让我们制作一张地图(下面的屏幕截图)。默认情况下,标签放置在点的坐标和多边形/多边形的坐标处path.centroid(d)
+ 简单的左对齐或右对齐,因此它们经常发生冲突。
手工制作的标签位置
一项改进I met需要添加一个人造的IF
修复,并根据需要添加尽可能多的内容,例如:
.attr("dy", function(d){ if(d.properties.name==="Berlin") {return ".9em"} })
随着要调整的标签数量增加,整体变得越来越脏:
//places's labels: point objects
svg.selectAll(".place-label")
.data(topojson.object(de, de.objects.places).geometries)
.enter().append("text")
.attr("class", "place-label")
.attr("transform", function(d) { return "translate(" + projection(d.coordinates) + ")"; })
.attr("dy", ".35em")
.text(function(d) { if (d.properties.name!=="Berlin"&&d.properties.name!=="Bremen"){return d.properties.name;} })
.attr("x", function(d) { return d.coordinates[0] > -1 ? 6 : -6; })
.style("text-anchor", function(d) { return d.coordinates[0] > -1 ? "start" : "end"; });
//districts's labels: polygons objects.
svg.selectAll(".subunit-label")
.data(topojson.object(de, de.objects.subunits).geometries)
.enter().append("text")
.attr("class", function(d) { return "subunit-label " + d.properties.name; })
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
.attr("dy", function(d){
//handmade IF
if( d.properties.name==="Sachsen"||d.properties.name==="Thüringen"|| d.properties.name==="Sachsen-Anhalt"||d.properties.name==="Rheinland-Pfalz")
{return ".9em"}
else if(d.properties.name==="Brandenburg"||d.properties.name==="Hamburg")
{return "1.5em"}
else if(d.properties.name==="Berlin"||d.properties.name==="Bremen")
{return "-1em"}else{return ".35em"}}
)
.text(function(d) { return d.properties.name; });
需要更好的解决方案
对于较大的地图和标签集来说,这是无法管理的。如何向这两个类添加力斥力:.place-label
and .subunit-label
?
这个问题是一场头脑风暴,因为我还没有截止日期,但我对此很好奇。我正在考虑这个问题作为 Migurski/ 的基本 D3js 实现Dymo.py。 Dymo.py 的 README.md 文档设定了一大组目标,从中选择核心需求和功能(20% 的工作,80% 的结果)。
-
初始安置:Bostock 在相对于地理点的左/右定位方面取得了良好的开端。
-
标签间排斥力:可能有不同的方法,Lars 和 Navarrc 分别提出了一种方法,
-
标签消灭:当一个标签的整体排斥力太强(因为被挤压在其他标签之间)时,一种标签消灭功能,消灭的优先级可以是随机的,也可以是基于
population
数据值,我们可以通过 Natural Earth .shapefile 获得。
- [奢华]标签与点的斥力:具有固定点和移动标签。但这是相当奢侈的。
我忽略标签排斥是否可以跨标签层和类别起作用。但让国家标签和城市标签不重叠也可能是一种奢侈。