Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the position of the legend in ggplot2

Tags:

r

ggplot2

I would like to position the legend inside the plotting area (top-left corner) and also need to remove the legend title. My code is shown below.

male <- structure(list(x1 = c(77.34,75.37,63.10,81.43,87.63,93.02,65.53,84.10,65.15,78.56), y1 = c(36.95,40.05,31.60,47.47,50.36,49.48,39.90,48.43,32.00,42.79)), .Names = c("x1", "y1"), class = "data.frame", row.names = c(NA,-10L))
female <- structure(list(x2 = c(42.39,38.77,44.43,42.37,48.79,46.00,53.71,47.38,43.75,46.95,52.62,43.50,55.91,43.45,35.02), y2 = c(20.65,21.28,19.27,20.49,24.99,24.21,28.16,28.15,18.82,20.03,25.90,18.54,34.40,20.80,16.31)), .Names = c("x2", "y2"), class = "data.frame", row.names = c(NA, -15L))
library(reshape2)
library(ggplot2)
names(female) <- c("x1", "y2")
df <- rbind(melt(male, id.vars = "x1"), melt(female, id.vars = "x1"))
ggplot(df, aes(x1, y = value, colour = variable)) + 
  geom_point(size=3) +theme(axis.text=element_text(size=14),
        axis.title=element_text(size=14,face="bold")) + theme(legend.text=element_text(size=12)) + labs(x = "x axis", y = "y axis")+ ylim(0,100) + xlim(0,100) + scale_colour_manual(values = c("red", "blue"), labels = c("male", "female"))
like image 429
ameya Avatar asked Feb 16 '16 05:02

ameya


1 Answers

Add legend.justification=c(1,1), legend.position=c(1,1),legend.title=element_blank() to your theme:

ggplot(df, aes(x1, y = value, colour = variable)) + 
  geom_point(size=3) +
  theme(axis.text=element_text(size=14),
        axis.title=element_text(size=14,face="bold"),
        legend.text=element_text(size=12),
        legend.justification=c(1,1),legend.position=c(1,1),legend.title=element_blank()
        ) + 
  labs(x = "x axis", y = "y axis") + 
  ylim(0,100) + 
  xlim(0,100) + 
  scale_colour_manual(values = c("red", "blue"), labels = c("male", "female"))

enter image description here

like image 61
Liesel Avatar answered Oct 15 '22 11:10

Liesel