簡體   English   中英

減少ggplot2中圖例列之間的空間

[英]Decreasing space between legend columns in ggplot2

這是一些示例代碼,其中提供了兩列的圖例。 我想減少圖例的兩個列之間的間隔(見下文)。

library(ggplot2)

labels <- c(expression(""^13*CH[4]),
            expression(""^13*CH[4]~"+"~SO[4]^{2-''}),
            expression(""^13*CH[4]~"+"~MoO[4]^{2-''})) 

ggplot(aes(mpg, wt, colour = factor(cyl), shape=factor(cyl)), 
       data = mtcars) +
      geom_point() +
      scale_colour_manual(values=c("red", "green", "blue"), label=labels)+
      scale_shape_manual(values = c(4,5,6), label=labels)+
      theme(legend.position = "bottom",
            legend.text.align = 0,
            legend.text = element_text(size=8),
            legend.key.size = unit(0.8, 'lines')) + 
      guides(col = guide_legend("", ncol=2), shape=guide_legend("", col=2))

這是我的現實生活中的問題: 在此處輸入圖片說明

在圖的右側需要額外的空間,因為那里的三個因子級別包含更多的字符。 但是,我的地塊大小確實受到限制。 因此,我想減少圖例兩行之間的空間。 我還想保持左側最底端的因子水平不變,而不添加額外的線。

根據您的示例,我對其進行了簡化:

創建有問題的情節:

library(ggplot2)

labels <- c("short1", "loooooooooooooooooong", "short2")

plt <- ggplot(aes(mpg, wt, colour = factor(cyl), shape=factor(cyl)), 
       data = mtcars) +
  geom_point() +
  scale_colour_manual(values=c("red", "green", "blue"), label=labels)+
  scale_shape_manual(values = c(4,5,6), label=labels)+
  theme(legend.position = "bottom",
        legend.text.align = 0,
        legend.text = element_text(size=8),
        legend.key.size = unit(0.8, 'lines')) + 
  guides(col = guide_legend("", ncol=2), shape=guide_legend("", col=2))
plot(plt)

圖例與圖例分開

提取圖例並進行調整

我使用以下答案從劇情中提取了圖例:

#Extract Legend 
g_legend<-function(a.gplot){ 
  tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
  legend <- tmp$grobs[[leg]] 
  return(legend)} 

legend <- g_legend(plt) 

並打印:

grid.newpage()
grid.draw(legend) 

情節傳說

然后,我探索了圖例中的小樣,發現了寬度字段:

legend$grobs[[1]]$widths
 [1] 0.2cm              0cm                0.1524cm           0.4064cm           0.0762cm           3.22791666666667cm 0.0762cm           0.4064cm           0.0762cm          
[10] 0.79375cm          0.2cm             
> 

顯然,這些3.227厘米太大了,所以我只更改了它們:

legend$grobs[[1]]$widths[6] <- unit(1.5, "cm")

並繪制:

grid.newpage()
grid.draw(legend)

傳奇但更緊湊

將修訂應用於全局圖:

最后的步驟是在ggplot上復制它:

將相同的手動校正應用於全局圖:

# this is how the legend was extracted:
plt_gtable <- ggplot_gtable(ggplot_build(plt)) 
leg <- which(sapply(plt_gtable$grobs, function(x) x$name) == "guide-box") 

# Replace the legend with our modified legend:
plt_gtable$grobs[[leg]] <- legend

並重新繪制:

grid.newpage()
grid.draw(plt_gtable)

DONE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM