How should I change the size of symbols in legends? I checked the document of theme
but found no answer.
Here is an example:
library(gg
You can make these kinds of changes manually using the override.aes
argument to guide_legend()
:
g <- g + guides(shape = guide_legend(override.aes = list(size = 5)))
print(g)
You should use:
theme(legend.key.size = unit(3,"line"))
If you want to change the sizes of 2 components of a legend independently, it gets trickier, but it can be done by manually editing the individual components of the plot using the grid
package.
Example based on this SO answer:
set.seed(1)
dat <- data.frame(x = runif(n = 100),
x2 = factor(rep(c('first', 'second'), each = 50)))
set.seed(1)
dat$y = 5 + 1.8 * as.numeric(dat$x2) + .3 * dat$x + rnorm(100)
# basic plot
g <- ggplot(data = dat,
aes(x = x, y = y, color = x2))+
theme_bw()+
geom_point()+
geom_smooth(method = 'lm')
# make the size of the points & lines in the legend larger
g + guides(color = guide_legend(override.aes = list(size = 2)))
# Make JUST the legend points larger without changing the size of the legend lines:
# To get a list of the names of all the grobs in the ggplot
g
grid::grid.ls(grid::grid.force())
# Set the size of the point in the legend to 2 mm
grid::grid.gedit("key-[-0-9]-1-1", size = unit(4, "mm"))
# save the modified plot to an object
g2 <- grid::grid.grab()
ggsave(g2, filename = 'g2.png')
Marius's answer did not work for me as of R version 3.2.2. You can still call guide_legend()
with the same override.eas
argument but you will need to specify color
instead of shape
in the wrapper function.
So if you're running a later version of R, try this instead:
g + guides(color = guide_legend(override.aes = list(size=5)))
EDIT
As pointed out by @Ibo in the comment, this may have been due to the color scale in the ggplot
object. If the ggplot
object has contains a color scale, the mapping of size (size=5
) has to be set on the color instead.