Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the legend box size in ggplot/ggplot2

Tags:

r

ggplot2

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?

like image 651
mmuurr Avatar asked Feb 04 '19 18:02

mmuurr


1 Answers

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.

like image 72
Matt Nolan Avatar answered Sep 21 '22 18:09

Matt Nolan