Q: How to add a legend in ggplot to my graph Hi have some code to simulate a Gaussian process. Please can someone help me add a legend to my plots on the top right corner. I want to state the different parameter values for each of the line styles/colours, e.g. l=1, l=5, l=10. Thanks.
# simulate a gaussian process
simGP = function(K){
  n = nrow(K)
  U = chol(K) # cholesky decomposition
  z = rnorm(n)
  c(t(U) %*% z)
}

# choose points to simulate the covariance.
x = seq(-1, 1, length.out = 500)


# Exponential kernel ------------------------------------------------------



kernel_exp = function(x, l = 1) {
  d = as.matrix(dist(x))/l
  K = exp(-d)
  diag(K) = diag(K) + 1e-8
  K
}

{y1 = simGP(kernel_exp(x,l=10))
y2 = simGP(kernel_exp(x,l=1))
y3 = simGP(kernel_exp(x,l=0.1))
data1 <- as.data.frame(x,y1)
data2 <- as.data.frame(x,y2)
data3 <- as.data.frame(x,y3)
df=data.frame(data1,data2,data3)

ggplot() + 
  geom_line(data=data1, aes(x=x, y=y1), color="green4", linetype = "twodash", size=0.5) + 
  geom_line(data=data2, aes(x=x, y=y2), color='red', linetype="longdash", size=0.5) +
  geom_line(data=data3, aes(x=x, y=y3), color='blue') +
  scale_color_manual(values = colors) +
  theme_classic() +
  labs(x='input, x',
       y='output, f(x)')+
  theme(axis.text=element_text(size=16),
        axis.title=element_text(size=14))}


A: You can do it using a dataframe variable to group the linetype and colour.
If you want to specify color and linetype, use scale_color_discrete and scale_linetype_discrete
y1 = simGP(kernel_exp(x,l=10))
y2 = simGP(kernel_exp(x,l=1))
y3 = simGP(kernel_exp(x,l=0.1))
data1 <- data.frame(x, y = y1, value = "10")
data2 <- data.frame(x, y = y2, value = "1")
data3 <- data.frame(x, y = y3, value = "0.1")
df=rbind(data1,data2,data3)

ggplot(data = df, aes(x=x, y=y, color = value, linetype = value, group = value)) + 
  geom_line(size=0.5) + 
  theme_classic() +
  labs(x='input, x',
       y='output, f(x)')+
  theme(axis.text=element_text(size=16),
        axis.title=element_text(size=14))

