Automatic label placement along path
A method for automatically finding the best eligible label position and size for a label that's going to go along a path inside of an area. This is potentially suitable for area charts where the area being labeled has a clear direction the text should "flow" in.
The basic approach is a crude one: test a center point at a certain font size, and work outwards to the left and right and disqualify it if you ever hit the side of the chart or run out of vertical space. If it fits, try a bigger size. If not, try a smaller size. Rinse/repeat until you've either found the largest size that will fit at that position or found that nothing will fit. Repeat with each possible center point until you've found the largest font size you can use, and where to put it.
Notes:
- This adds a small optimization of disqualifying any candidate points that involve a sharp angle turn, because text turning at a sharp angle can be pretty hard to read.
- Another optimization that's omitted for brevity is to first try to use a flat label if the area is blobby enough (e.g. if your area is basically a circle putting a label "along" its midline doesn't really make sense).
- It might be a good idea to optimize for more than just fit - for example, it's probably better to have labels at similar x positions, or to have them read left-to-right from top to bottom rather than having to jump back and forth.
- This is a pretty brute force approach and could probably be a lot smarter, but since the operations are all plain arithmetic, it really doesn't seem like a big deal. Even with the loops within loops, this example takes about 10 microseconds to check all the possible positions for an area. You could shave it down further by considering fewer font sizes or fewer x positions.
- Measuring the available space vertically is a little bit off since the text might be rotated, but it seems to generally work out OK as long as the area doesn't contain crazy angles. This example tries to get a little more precise by calculating the rotated clearance.
See also:
Automatic label placement along a path #2
Streamgraph label positions #2
Stacked area label placement #2