how do I reduce the gap between two guides in one plot. In the example below, the two guides are from a color and size scale and I want to change the gap between the two so
Now it seems to be possible using the theme parameters:
ggplot(df,aes(x=x,y=y,color=color,size=size)) + geom_point() +
theme(legend.spacing.y = unit(-0.5, "cm"))
You can also try to decrease margins of the legends:
legend.margin = margin(-0.5,0,0,0, unit="cm")
or older
legend.margin=unit(0, "cm")
I tried to play to customize legend
or guide
parameters but I can't find a solution. I hope give a solution using ggplot2 settings.
Here 2 solutions based on the gtable
and grid
packages.
for the gtable
solution, the code is inspired from this question.
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)
Similar using the grid
package ( we redraw in the viewport of the legend)
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)