Smaller gap between two legends in one plot (e.g. color and size scale)

后端 未结 2 539
有刺的猬
有刺的猬 2020-12-14 09:08

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

相关标签:
2条回答
  • 2020-12-14 09:49

    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")
    
    0 讨论(0)
  • 2020-12-14 09:56

    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.

    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)
    

    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)
    
    0 讨论(0)
提交回复
热议问题