ggplot2 increase space between legend keys

前端 未结 2 1146
说谎
说谎 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: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)

提交回复
热议问题