Plotting two variables as lines using ggplot2 on the same graph

后端 未结 5 2184
不思量自难忘°
不思量自难忘° 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:12

    The general approach is to convert the data to long format (using melt() from package reshape or reshape2) or gather()/pivot_longer() from the tidyr package:

    library("reshape2")
    library("ggplot2")
    
    test_data_long <- melt(test_data, id="date")  # convert to long format
    
    ggplot(data=test_data_long,
           aes(x=date, y=value, colour=variable)) +
           geom_line()
    

    ggplot2 output

    Also see this question on reshaping data from wide to long.

提交回复
热议问题