Measures the legend height relative to the plot panel and automatically
wraps the legend into multiple columns if it would overflow. This function
must be called on a complete ggplot object, not added with +.
Details
This function builds the plot to measure actual dimensions, then rebuilds
with an appropriate number of legend rows if the legend is too tall.
It's particularly useful after applying legend_style(angle = 90)
which can cause legends to exceed the plot height.
Because this requires building the plot twice, it has a small performance cost. For static plots this is negligible.
Examples
library(ggplot2)
# Legend with rotated text that might overflow
p <- ggplot(mpg, aes(displ, hwy, color = class)) +
geom_point() +
legend_style(angle = 90)
# Auto-fit will wrap if needed
legend_auto_fit(p)