Why my codes is unable to add legend to figure in ggplot2

Viewed 27

I want to add some legend to this figure. There are one set of scatter points and two lines. Below is my codes. plot

rm(list = ls()) 
n=500
set.seed(100)
x1=seq(from=-3,to=3,length.out = n)
a=rnorm(n,mean=0,sd=0.2)

z=1+2*x1+a
p=1/(1+exp(-z))
y=(p>=(runif(n,min=0.4,max=0.6)))*1


X=data.frame(x1=x1,y=y)
K=glm(formula=y~x1,family=binomial(link="logit"),data=X)

p_fit=1/(1+exp(-(K$coefficients[1]+K$coefficients[2]*x1)))

ggplot()+  xlab("x1")+  ylab("y")+facet_grid()+
  geom_point(data=data.frame(x1,y), aes(x=x1, y=y),size=4)+
  geom_line(data=data.frame(x1,p), aes(x=x1, y=p),size=1.2,col="blue")+
  geom_line(data=data.frame(x1,p_fit), aes(x=x1, y=p_fit),size=1.5,col="red")+
  theme(legend.position =c(0.8,0.5))
1 Answers

In ggplot legends appear when you map a variable or a constant to an aesthetic. In your case, try as follow.

ggplot() +
    geom_point(data = data.frame(x1, y), aes(x = x1, y = y), size = 3, alpha = 0.5)+
    geom_line(data = data.frame(x1, p),
              aes(x = x1, y = p, color = 'p'),
              size = 1.2) +
    geom_line(data = data.frame(x1, p_fit),
              aes(x = x1, y = p_fit, color = "p_fit"), size = 1.5) +

    xlab("x1") +
    ylab("y")+
    theme(legend.position = c(0.8, 0.5)) +
    scale_color_manual(values =  c("blue", "red"))

enter image description here

Related