ggplot2增加图例按键之间的间距

ggplot2增加图例按键之间的间距

问题描述:

如何增加图例中ggplot2图例的按键之间的间距?ggplot2增加图例按键之间的间距

library(ggplot2) 
ggplot(aes(mpg, wt, colour = factor(cyl)), 
     , data = mtcars) + 
     geom_point() + 
    theme(legend.direction = "horizontal", 
     legend.position = "bottom") + 
    guides(color = guide_legend(nrow=2)) 

enter image description here

我找的是,在上述的情节增添了一种垂直调节(键4和键6)之间的GGPLOT2的选择吗?我应该创建一个自定义图例密钥吗?

PS:我想增加标签之间的框之间的空白区域。

所需的情节是:

enter image description here

注:没有问题不重复的其他问题。我们希望在这里添加已经在多行中的项目之间的垂直间距。在另一个问题中,我们有一行图例,我们希望在项目之间添加空格(水平)。

+1

的[这]可能的复制(http://stackoverflow.com/问题/ 11366964/IS-有-A-方式对变化的间距之间 - 传奇项功能于GGPLOT2)。这是否解决了你的问题? – Heroka

+0

@Heroka no.it不是重复的。我不想更改密钥大小。只是键之间的空间。您可以尝试链接中的解决方案来检查此问题。 – agstudy

+0

'grid'或'gridExtra'可能会有所帮助,但我从来没有使用过很多... ['gridExtra' vignette](https://github.com/baptiste/gridextra/wiki/arrange-ggplot#Legends)看起来有些有希望,但远不能提供明确的解决方案。 – maj

的替代(和可能更容易)解决方案,在你的代码的theme部分使用legend.keylegend.key.size

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

这给:

enter image description here


如果你操纵的传说之前调用theme_bwtheme_classic,你应该设置传说矩形的颜色:

legend.key = element_rect(size = 5, color = 'white') #or: color = NA 
+0

您能解释'legend.key'的大小属性和'legend.key.size'的'lines'属性之间的区别吗?哪一个控制键之间的间距(即,灰色框+标签)? –

+0

@BerkU。 'legend.key'的size参数决定了边界线的大小。 'legend.key.size'的'lines'属性决定整个盒子的大小。 – Jaap

+0

这并没有解决我的情况,因为''lines''使得一些图例符号与框一起增加。在我的情况下,点符号没有增加(与你的例子相同),但是线符号没有增加。由于我的线条是垂直的,随着“线条”的增加,盒子不断增大,而不增加图例两列之间的空间。如果我找到解决方案,会报告回来。 – PatrickT

这里使用gtable的解决方案。基本上,我提取传奇grobs表,并在传奇表中添加一行。

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:我不”这里知道如何表再次强迫一个阴谋!也许别人可以帮助这里(我只是绘图,并失去了对象结构)

enter image description here