Bostock的 “让我们创建一张地图”
迈克·博斯托克(Mike Bostock)的 让我们创建一张地图 (下面是截图)。默认情况下,标签会放置在点的坐标和多边形 / 多重多边形的 path.centroid(d)
+ 简单的左对齐或右对齐,因此它们经常发生冲突。
手工标签放置
我遇到的一个改进方法需要添加一个人工制作的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
和 .subunit-label
添加力斥功能?
这个问题相当棘手,因为我没有截止日期,但我非常好奇。我将这个问题视为 Migurski/Dymo.py 的基本 D3js 实现。Dymo.py 的 README.md 文档设置了大量的目标,我们从中选择核心需求和功能(20% 的工作量,80% 的结果)。
- 初始放置: Bostock 通过相对于地理点的左/右位置给出一个好的开始。
- 标签间的斥力: 可以采用不同的方法,Lars 和 Navarrc 分别提出了一种方法。
- 标签消除: 当一个标签的整体斥力太强时,由于被夹在其他标签之间,需要一个标签消除函数,优先级可以是随机的或者基于
population
数据值,我们可以通过 NaturalEarth 的 .shp 文件获取该值。 - [豪华] 标签与点的斥力: 固定的点和移动的标签。但这只是一种奢侈品。
我不知道标签斥力是否适用于跨层和标签类别。但避免国家标签和城市标签重叠可能也是一种奢侈。