title: R ggplot2: Change the spacing between the legend and the panel
body: <p>How do I change the spacing between the legend area and the panel in <code>ggplot2 2.2.0</code>?</p>
  
  <p><a href="https://i.stack.imgur.com/sYPUL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sYPUL.png" alt="enter image description here"></a></p>
  
  <pre><code>library(ggplot2)
  library(dplyr)
  library(tidyr)
  
  dfr &lt;- data.frame(x=factor(1:20),y1=runif(n=20)) %&gt;%
          mutate(y2=1-y1) %&gt;%
          gather(variable,value,-x)
  
  
  ggplot(dfr,aes(x=x,y=value,fill=variable))+
    geom_bar(stat="identity")+
    theme(legend.position="top",
          legend.justification="right")
  </code></pre>
  
  <p>Changing <code>legend.margin</code> or <code>legend.box.margin</code> doesn't seem to do anything.</p>
  
  <pre><code>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))
  </code></pre>