22

如何减少一个情节中两个指南之间的差距。在下面的示例中,两个指南来自颜色和大小比例,我想更改两者之间的差距,以便标题“大小”正好低于 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()

编辑:这是情节。我想让绿线和箭头突出显示的间隙变小。

在此处输入图像描述

4

2 回答 2

34

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

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

您还可以尝试减少图例的边距:

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

或更老

legend.margin=unit(0, "cm")
于 2017-03-10T11:01:18.457 回答
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)

使用包类似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)
于 2013-01-01T10:26:46.303 回答