Reputation: 1580
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?
Upvotes: 20
Views: 43538
Reputation: 41
@Z.lin had the right approach in the comments. Based on https://wilkelab.org/cowplot/articles/shared_legends.html this might look something like:
library(ggplot2)
library(cowplot)
Make a ggplot object
my_plot <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, colour = Species))+
geom_point()
Extract the legend
my_legend <- get_legend(
# create some space to the left of the legend
my_plot + theme(legend.box.margin = margin(0, 0, 0, 12))
)
Re-plot your plot in a grid without the legend (can combine multiple plots here if desired)
my_plot_nl <- <- plot_grid(
my_plot + theme(legend.position="none"),
align = 'vh',
hjust = -1,
nrow = 1
)
Recombine your legend-free plot and legend and specify the relative width of each. The plot now takes up 3/4 of the plot width and the legend 1/4.
plot_grid(my_plot_nl, my_legend, rel_widths = c(3,1))
If you do this for each plot, making sure to use the same rel_widths
and saving the figures using the same dimensions, the plot area and legend should be consistent across them.
Upvotes: 4
Reputation: 57
You might attempt to change your theme
call as follows:
theme(legend.margin =margin(r=10,l=5,t=5,b=5))?
Upvotes: -2
Reputation: 698
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.
Upvotes: 29