R – How to specify the legend box size in ggplot/ggplot2

ggplot2r

In R/ggplot2, I have multiple plots, each of which has a legend box.
I want the legend box to be the same width for each plot, but ggplot2 tries to dynamically size the legend box based on the legend name, key values, etc. (which are unique to each plot).
The various plots must fit into a specified publication slot, with a specified width for the legend, and the plots must be made separately (so faceting to guarantee identical legend widths across the plots isn't possible).
Looking at theme I couldn't find an option to specify the legend box width … any ideas?

Best Answer

To specify the legend box size you could use + theme(legend.key.size = unit(2, "cm")).

library(tidyverse)
tb <- tibble(a = 1:10, b = 10:1, c = rep(1:2, 5))

ggplot(tb, aes(a, b, colour = c)) +
  geom_point() +
  theme(legend.key.size = unit(0.2, "cm"))

More details and additional modifications are here and under the keywidth argument here.