繁体   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