Smaller gap between two legends in the same plot (e.g. color and scale)

How to reduce the gap between two guides in one graph. In the example below, the two manuals relate to the color and size scale, and I want to change the gap between them so that the heading “size” is below the legend point for 1. Structurally, this might not make sense in this example, but in my actual application it does.

df=data.frame(x=rnorm(100),y=rnorm(100),color=factor(rbinom(100,1,0.5)),size=runif(100)) ggplot(df,aes(x=x,y=y,color=color,size=size)) + geom_point() 

Edit: Here is the plot. I would like to make the selection of a space with a green line and an arrow less.

enter image description here

+6
source share
2 answers

I tried to play to adjust the legend or guide parameters, but I can not find a solution. I hope you get a solution using ggplot2 settings.

Here are 2 solutions based on the gtable and grid packages.

to solve gtable , the code is inspired by this question .

enter image description here

  library(gtable) # Data transformation data <- ggplot_build(p) gtable <- ggplot_gtable(data) # Determining index of legends table lbox <- which(sapply(gtable$grobs, paste) == "gtable[guide-box]") # changing the space between the 2 legends: here -0.5 lines guide <- gtable$grobs[[lbox]] gtable$grobs[[lbox]]$heights <- unit.c(guide$heights[1:2], unit(-.5,'lines'), ## you can the GAP here guide$heights[4:5]) # Plotting grid.draw(gtable) 

Similarly, using the grid package (we redraw the legend in the viewport)

 pp <- grid.get('guide',grep=T) depth <- downViewport(pp$wrapvp$name) guide <- grid.get('guide',grep=T) grid.rect(gp=gpar(fill='white')) guide$heights <- unit.c(guide$heights[1:2],unit(-0.2,'lines'),guide$heights[4],unit(0.1,'lines')) grid.draw(guide) upViewport(depth) 
+5
source

Now you can use theme options:

 ggplot(df,aes(x=x,y=y,color=color,size=size)) + geom_point() + theme(legend.spacing.y = unit(-0.5, "cm")) 

You can also reduce the boundaries of legends:

 legend.margin = margin(-0.5,0,0,0, unit="cm") 

or older

 legend.margin=unit(0, "cm") 
+8
source

All Articles