简体   繁体   中英

Decreasing space between legend columns in ggplot2

Here is some example code, which provides a legend with 2 columns. I want to decrease the space between the two colums of the legend (see below).

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

Here is my real life problem: 在此处输入图片说明

Additional space is needed on the right side of the plot, because the three factor levels there contain much more characters. However, i am really constrained in the plot size. Hence, I would like to decrease the space between the two rows of the legend. I also would like to keep the most bottom factor level of the left hand side as is, without adding an extra line.

Based on your example, I simplified it a bit:

Create the problematic plot:

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 the legend and tweak it

I used this answer to extract the legend from the plot:

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

And print it:

grid.newpage()
grid.draw(legend) 

情节传说

Then I explored the grobs inside the legend and I found the widths field:

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             
> 

Apparently those 3.227 cm are too much so I just changed them:

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

And plot it:

grid.newpage()
grid.draw(legend)

传奇但更紧凑

Apply the fix to the global plot:

The final steps are to replicate that on the ggplot:

Apply that same manual correction to the global plot:

# 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

And replot:

grid.newpage()
grid.draw(plt_gtable)

DONE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM