30

How do I change the spacing between the legend area and the panel in 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")

Changing legend.margin or legend.box.margin doesn't seem to do anything.

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))
0

1 Answer 1

36

Actually, I think the options you mentioned will work. They seem to work for me; perhaps you didn't input appropriate values.

Have a look at these 2 to see what I'm talking about:

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))

enter image description here

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))

enter image description here

2
  • 1
    ah yes! It does work. Thanks. The values have changed a lot. Dec 28, 2016 at 13:26
  • 5
    Isn't that strange though? A margin of 0 should already bring it very close to the graph? Does it mean there is another margin element that we are overlapping on by setting a negative margin?
    – Matifou
    Jul 3, 2019 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.