ggplot2 increase space between legend keys

前端 未结 2 1133
说谎
说谎 2020-12-05 17:15

How can I increase the space between the keys of the legend of ggplot2 plot?

library(ggplot2)
ggplot(aes(mpg, wt, colour = factor(cyl)),
                


        
相关标签:
2条回答
  • 2020-12-05 17:35

    An alternative (and probably easier) solution is using legend.key and legend.key.size in the theme part of your code:

    ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
      geom_point() +
      guides(color = guide_legend(nrow = 2)) +
      theme(legend.direction = 'horizontal', 
            legend.position = 'bottom',
            legend.key = element_rect(size = 5),
            legend.key.size = unit(1.5, 'lines'))
    

    this gives:


    In case you are calling theme_bw or theme_classic before manipulating the legend, you should set the color of the legend rectangle:

    legend.key = element_rect(size = 5, color = 'white') #or: color = NA
    
    0 讨论(0)
  • 2020-12-05 17:46

    Here a solution using gtable. Basically I am extracting legend grobs table and I add a row in the legend table.

    library(gtable)
    library(grid)
    ## transform the ggplot to a grobs table
    p_table <- ggplot_gtable(ggplot_build(p))
    ## extract legend
    leg <- which(sapply(p_table$grobs, function(x) x$name) == "guide-box")
    ## this is the tricky part !
    ## add  a row in the second position (pos=2)
    p_table$grobs[[leg]]$grobs[[1]] <- 
      gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]], 
                      unit(0.5, "line"), ## you can increase the height here
                      pos=2)             ## since I have 2 rows , I insert it in the middle
    plot(p_table)  
    

    PS: I dont' know here how to coerce the table to a plot again! maybe someone else can help here ( I am just plotting it and losing the object structure)

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