0
x  <- seq(0, 50, 1) 
y1 <- exp(0.0509*x)
y2 <- exp(0.0519*x)
df <- data.frame(x,y1,y2)

ggplot(df, aes(x)) +                    
  geom_line(aes(y=y1), colour="blue") +  
  geom_line(aes(y=y2), colour="red")

According to the code, I would like how to add a legend called "group 1" for y1 and "group 2" for y2. I've tried many things that I've seen on this forum, but I always get an error.

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
S12000
  • 3,345
  • 12
  • 35
  • 51

1 Answers1

1

Use this:

library(reshape2)
library(ggplot2)
gg <- melt(df,id="x")
ggplot(gg, aes(x=x, y=value, color=variable))+
  geom_line()

jlhoward
  • 58,004
  • 7
  • 97
  • 140