plot icon indicating copy to clipboard operation
plot copied to clipboard

A better “label centroid” initializer? (polylabel)

Open Fil opened this issue 2 years ago • 5 comments

The centroid of a geometry is sometimes outside of it, for example (but not exclusively) with a MultiPolygon such as France+Guyane. This can result in labels or interactive tips that are quite far off from the shape they identify.

A great solution is to use @mapbox/polylabel, which guarantees that the center is inside —and furthermore at an optimal position for a centered label. The dependency is less that 1kB over the wire, including tinyqueue. An alternative approach could be to add an option to Plot.centroid, to make it choose the centroid of the largest polygon when given a multipolygon. Subpar solution, but cheaper.

Prototype https://observablehq.com/@observablehq/plot-pole-of-inaccessibility-1587

Fil avatar May 18 '23 21:05 Fil

the centroid of the largest polygon could also lead to the point being outside the polygon. this would be the case for a crescent-moon shaped polygon.

polylabel sounds great!

fgregg avatar Aug 02 '23 14:08 fgregg

We should probably call it labelCentroid, with an ellipseRatio option that defaults to 2 (?). And maybe add an anchor option so that we can align text on the left (with textAnchor: start) or on the right (with textAnchor: end). Since polylabel returns the radius, it's not expensive to add.

Fil avatar Aug 02 '23 15:08 Fil

this approach could also make it easier to scale labels so they fit inside of polygons, since you'll know the ellipse dimensions anyway.

fgregg avatar Aug 02 '23 16:08 fgregg

See https://github.com/observablehq/plot/issues/2087#issuecomment-2169156629 for using this as part of a "geo" pointer option.

Fil avatar Jun 17 '24 15:06 Fil

Related:

Fil avatar Jun 17 '24 15:06 Fil