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

rmf*_*rmf 13 r ggplot2

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

在此输入图像描述

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

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

小智 13

有一个主题选项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)
Run Code Online (Sandbox Code Playgroud)

这是原始版本和调整后的版本

原来的与 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
Run Code Online (Sandbox Code Playgroud)

没有 legend.box.spacing 和 legend.margin

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


Hac*_*k-R 12

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

看看这些2,看看我在说什么:

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

在此输入图像描述

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

在此输入图像描述

  • 那不是很奇怪吗?边距0应该已经非常接近图形了吗?这是否意味着我们通过设置负边距重叠了另一个边距元素? (2认同)