减少ggplot2中图例列之间的空间

时间:2017-03-17 14:14:16

标签: r ggplot2

以下是一些示例代码,它提供了包含2列的图例。我想减少图例的两个列之间的空间(见下文)。

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

这是我的真实生活问题: enter image description here

在图的右侧需要额外的空间,因为那里的三个因子级别包含更多的字符。但是,我的情节大小确实受到限制。因此,我想减少图例的两行之间的空间。 我还希望保持左侧最底部因素水平,而不添加额外的线。

1 个答案:

答案 0 :(得分:3)

根据您的示例,我对其进行了简化:

创建有问题的情节:

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)

plot with legend separated

提取图例并进行调整

我使用this answer从图中提取图例:

#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 of the plot

然后我探索了图例中的凹凸,我找到了宽度字段:

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)

legend but more compact

将修复程序应用于全局图:

最后的步骤是在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