Plotting two variables as lines using ggplot2 on the same graph

后端 未结 5 2185
不思量自难忘°
不思量自难忘° 2020-11-21 05:41

A very newbish question, but say I have data like this:

test_data <-
  data.frame(
    var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
    var1 = 150 + c(0         


        
5条回答
  •  醉酒成梦
    2020-11-21 06:17

    I am also new to R but trying to understand how ggplot works I think I get another way to do it. I just share probably not as a complete perfect solution but to add some different points of view.

    I know ggplot is made to work with dataframes better but maybe it can be also sometimes useful to know that you can directly plot two vectors without using a dataframe.

    Loading data. Original date vector length is 100 while var0 and var1 have length 50 so I only plot the available data (first 50 dates).

    var0 <- 100 + c(0, cumsum(runif(49, -20, 20)))
    var1 <- 150 + c(0, cumsum(runif(49, -10, 10)))
    date <- seq(as.Date("2002-01-01"), by="1 month", length.out=50)    
    

    Plotting

    ggplot() + geom_line(aes(x=date,y=var0),color='red') + 
               geom_line(aes(x=date,y=var1),color='blue') + 
               ylab('Values')+xlab('date')
    

    However I was not able to add a correct legend using this format. Does anyone know how?

提交回复
热议问题