R ggplot2:改变图例和面板之间的间距

38

如何在 ggplot2 2.2.0 中更改图例区域和面板之间的间距?

enter image description here

library(ggplot2)
library(dplyr)
library(tidyr)

dfr <- data.frame(x=factor(1:20),y1=runif(n=20)) %>%
        mutate(y2=1-y1) %>%
        gather(variable,value,-x)


ggplot(dfr,aes(x=x,y=value,fill=variable))+
  geom_bar(stat="identity")+
  theme(legend.position="top",
        legend.justification="right")

更改legend.marginlegend.box.margin似乎没有任何效果。

ggplot(dfr,aes(x=x,y=value,fill=variable))+
  geom_bar(stat="identity")+
  theme(legend.position="top",
        legend.justification="right",
        legend.margin=margin(0,0,0,0),
        legend.box.margin=margin(0,0,0,0))
2个回答

46

实际上,我认为你提到的选项会起作用。它们对我来说似乎有效;也许你没有输入适当的值。

看一下这两个,就能明白我在说什么:

ggplot(dfr,aes(x=x,y=value,fill=variable))+
  geom_bar(stat="identity")+
  theme(legend.position="top",
        legend.justification="right",
        legend.margin=margin(0,0,0,0),
        legend.box.margin=margin(-10,-10,-10,-10))

输入图片说明

ggplot(dfr,aes(x=x,y=value,fill=variable))+
  geom_bar(stat="identity")+
  theme(legend.position="top",
        legend.justification="right",
        legend.margin=margin(0,0,0,0),
        legend.box.margin=margin(10,10,10,10))

在此输入图片描述


1
啊,是的!它起作用了。谢谢。这些值已经改变了很多。 - mindlessgreen
8
很奇怪,不是吗?0的边距应该已经让它非常接近图形了吧?这是否意味着我们通过设置负边距来覆盖了另一个边距元素呢? - Matifou
1
@Matifou 是的,事实证明确实有。请查看我的答案 https://dev59.com/lFgR5IYBdhLWcg3wZcq1#73880769 - nstjhp

10

有一个主题选项legend.box.spacing,可以调整图例和绘图区域之间的间距。

ggplot(dfr,aes(x=x,y=value,fill=variable))+
geom_bar(stat="identity")+
theme(legend.position="top",
      legend.justification="right", 
      legend.box.spacing = unit(0, "pt")) # The spacing between the plotting area and the legend box (unit)

以下是原始内容和调整后的内容:

originalwith legend.box.spacing=0

通过调整legend.margin,您也可以使图例与面板接触。

ggplot(dfr,aes(x=x,y=value,fill=variable))+
 geom_bar(stat="identity")+
 theme(legend.position="top",
       legend.justification="right", 
       legend.box.spacing = unit(0, "pt"),# The spacing between the plotting area and the legend box (unit)
       legend.margin=margin(0,0,0,0))# the margin around each legend

无图例框间距或图例边距

legend.box.margin没有效果(至少在灰色主题中)是因为它被定义为legend.box.margin = margin(0, 0, 0, 0, "cm")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接