Home > Back-end >  Grouping vector data to label for line graph
Grouping vector data to label for line graph

Time:03-12

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

CodePudding user response:

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

  • Related