How do I change the spacing between the legend area and the panel in 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")
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))
Control legend position with legend. You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.
For Moving the position of ggplot2 legend at any side of the plot, we simply add the theme() function to geom_point() function.
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With