Vertical alignment of text labels
This example demonstrates a label-collision-avoidance algorithm for stacked bar charts, showing how text labels can be repositioned to prevent overlap when bars are small or near the chart’s border. The visualization uses three colored sets of rectangles—red for the initial random positions, orange for labels after bottom-alignment adjustments, and green for the final corrected positions after top-alignment passes. Built with D3 v4 and rendered as SVG, the code computes bounding boxes and shifts overlapping rectangles vertically in one or two passes. The data consists of eight randomly generated y-coordinates, sorted in descending order, with labels drawn at fixed width and height.
AI-generated descriptionThis is an example how to compute the position of text labels for stacked bar charts. The challenge is to align the labels when the stacked areas are very small and next to each other leading to overlapping text labels. Or when a stacked area is very close to the border.
In order to simulate the algorithm, rectangles are drawn, corresponding to the bounding box of a text label. On the left, the rectangles are randomly initialized. In one or two passes the final position is computed. Reload page to see different initial seeting.
Built with blockbuilder.org