ggplot2: Adjust the symbol size in legends

后端 未结 4 1122
情话喂你
情话喂你 2020-11-30 02:36

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         


        
相关标签:
4条回答
  • 2020-11-30 03:14

    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)
    
    0 讨论(0)
  • 2020-11-30 03:20

    You should use:

    theme(legend.key.size = unit(3,"line"))
    
    0 讨论(0)
  • 2020-11-30 03:33

    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')
    

    0 讨论(0)
  • 2020-11-30 03:39

    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.

    0 讨论(0)
提交回复
热议问题