0

I have some data in the form of vectors which I place inside a data frame to use with ggplot. I have managed to output the data as a line graph and colour them separately but I am unsure how I might label each set of vector data so that I can somehow label each line graph to produce a legend so the diagram reads more clearly. I am super new to R and would appreciate any insight into how I might go about doing this.

Amount <- c(30, 60, 90, 125, 200, 250, 300)
Time <- c(1.6178,1.7141,1.9539,2.1827,2.6227,2.7161,3.0928)
Time3 <- c(1.7704,2.0969,2.3615,2.5359,3.6506,4.0699,4.5538)
Time4 <- c(2.5763,2.7251,2.7857,3.3977,4.7343,5.7973,6.4203)

df2 <- data.frame(var0 = c(Time),
                  var1 = c(Time3),
                  var2 = c(Time4))


TimeRange = range(0, 7)

plot <- ggplot(data=df2, aes(x=Amount, y=TimeRange)) +
  geom_line(aes( y = var0 ), color="blue")+
  geom_line(aes( y = var1 ), color="red") +
  geom_line(aes( y = var2 ), color="green")+
  geom_point(aes(y = var0)) + 
  geom_point(aes(y = var1)) +
  geom_point(aes(y = var2)) +

  ggtitle("LineGraph plot")

Current output enter image description here

Krellex
  • 613
  • 2
  • 7
  • 20
  • Possible duplicate: [Add legend to ggplot2 line plot](https://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) – stefan Mar 11 '22 at 22:18

1 Answers1

1

You can change the names in the scale_color_manual to what you want in this code:

Amount <- c(30, 60, 90, 125, 200, 250, 300)
Time <- c(1.6178,1.7141,1.9539,2.1827,2.6227,2.7161,3.0928)
Time3 <- c(1.7704,2.0969,2.3615,2.5359,3.6506,4.0699,4.5538)
Time4 <- c(2.5763,2.7251,2.7857,3.3977,4.7343,5.7973,6.4203)

df2 <- data.frame(var0 = c(Time),
                  var1 = c(Time3),
                  var2 = c(Time4))


TimeRange = range(0, 7)

plot <- ggplot(data=df2, aes(x=Amount, y=TimeRange)) +
  geom_line(aes( y = var0 , color="blue"))+
  geom_line(aes( y = var1 , color="red")) +
  geom_line(aes( y = var2 , color="green")) +
  geom_point(aes(y = var0)) + 
  geom_point(aes(y = var1)) +
  geom_point(aes(y = var2)) +
  scale_color_manual(name = "Legend", breaks = c("blue", "red", "green"),
                     values=c('blue'='blue', 'red'='red', 'green'='green')) +
  ggtitle("LineGraph plot")

plot

Output: enter image description here

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Thanks for this! Would it be possible to name the legend labels myself? Instead of setting them blue, red & green. I could set them to a custom name? – Krellex Mar 12 '22 at 06:20
  • 1
    @Krellex Yes absolutely! You can change in the `scale_color_manual` function the `name` of legend and names of the colors to what you want. – Quinten Mar 12 '22 at 09:04