2015-08-28 151 views
35

如何增加圖例中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

回答

39

的替代(和可能更容易)解決方案,在你的代碼的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

7

這裏使用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

相關問題