FLOURISH · CHART ENGINEERING
Responsive labels for pie charts
Even when a slice is easy to see, its label might not fit inside it. Flourish didn’t yet support placing labels outside pie or donut charts. I led the implementation and development of external labels and leader lines.
Before and after
Switch between internal and external labels on the same UK electricity chart. Look for the coal slice: its label appears outside the pie, with a leader line pointing back to the slice.
Single chart
Making room for labels and slices
My first implementation rendered and measured the labels, then made another pass to fit as many as possible without collisions. After feedback and discussion, I switched to a heuristic that calculated the candidate positions before rendering. It takes into account the number of slices, label length, font size and available space, but calculates these upfront before render. We expected it to place labels well in most cases, and it simplified the code and avoided repeated layout passes.
I built a D3 layout that arranges labels on either side of the pie and connects them to their slices with elbow leader lines. I used a spread function to space the labels vertically and hid any that still overlapped. When there were too many labels to fit, I dropped the ones with the longest leader lines first, keeping the labels closest to their slices.
I also updated the legend’s Auto setting. When labels already show category names and values, Auto can hide the legend. With value-only labels, the legend tells readers which category each slice represents.
Making the layout work at different sizes
I made the label layout recalculate as the available space changed. That mattered on narrow screens and in grids, where each pie has less room for labels.
Compare the four years below to see how the placement changes when each pie has less room.
Grid of charts
Crossfading labels when slices move
Filtering out a slice can shift the remaining slices and send a label to the other side of the pie. I implemented three versions of each label: one for each side of the pie, with the text aligned towards the chart, and a centred version for labels inside a slice. When a label switched sides, I crossfaded between the two alignments so the text did not travel across the chart.
I also made sure screen readers announced each label once, even though the chart rendered three versions.
Try it in the grid of charts with external labels selected. Filter out Wind & Solar (yellow) on the 2020 chart and watch the Nuclear label (light blue) crossfade to the other side.
Shipping a new default
External labels became the default for new pie and donut charts, with internal labels still available as an option. We shipped the change in a new major version of the template so existing charts kept their original layout.