Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2: Change the spacing between the legend and the panel

Tags:

r

ggplot2

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))
like image 934
rmf Avatar asked Dec 28 '16 13:12

rmf


People also ask

How do I change the position of my legend in R?

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.

How do I move the legend in ggplot2?

For Moving the position of ggplot2 legend at any side of the plot, we simply add the theme() function to geom_point() function.

How do I change the legend value in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I get rid of Ggplot legend?

By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.


1 Answers

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

like image 82
Hack-R Avatar answered Sep 21 '22 01:09

Hack-R