一个图中两个图例之间的间隙较小(例如颜色和大小比例)

use*_*795 12 r ggplot2

如何在一个图中缩小两个参考线之间的间隙.在下面的示例中,两个指南来自颜色和大小比例,我想更改两者之间的间隙,以便标题"大小"正好位于图例点下方1.设计方面,它可能不会感觉在这个例子中,但在我的实际应用程序中它.

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()
Run Code Online (Sandbox Code Playgroud)

编辑:这是情节.我想通过绿线突出显示间隙,箭头更小.

在此输入图像描述

Mel*_*.cz 19

现在似乎可以使用主题参数:

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

您还可以尝试降低图例的边距:

legend.margin = margin(-0.5,0,0,0, unit="cm")
Run Code Online (Sandbox Code Playgroud)

或更老

legend.margin=unit(0, "cm")
Run Code Online (Sandbox Code Playgroud)


ags*_*udy 5

我尝试播放自定义legendguide参数,但我找不到解决方案.我希望使用ggplot2设置提供解决方案.

这里有2个基于gtablegrid包的解决方案.

对于gtable解决方案,代码的灵感来自于这个问题.

在此输入图像描述

  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)
Run Code Online (Sandbox Code Playgroud)

类似使用grid包(我们在图例的视口中重绘)

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)
Run Code Online (Sandbox Code Playgroud)