Plotting two variables as lines using ggplot2 on the same graph

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

    Using your data:

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

    I create a stacked version which is what ggplot() would like to work with:

    stacked <- with(test_data,
                    data.frame(value = c(var0, var1),
                               variable = factor(rep(c("Var0","Var1"),
                                                     each = NROW(test_data))),
                               Dates = rep(Dates, 2)))
    

    In this case producing stacked was quite easy as we only had to do a couple of manipulations, but reshape() and the reshape and reshape2 might be useful if you have a more complex real data set to manipulate.

    Once the data are in this stacked form, it only requires a simple ggplot() call to produce the plot you wanted with all the extras (one reason why higher-level plotting packages like lattice and ggplot2 are so useful):

    require(ggplot2)
    p <- ggplot(stacked, aes(Dates, value, colour = variable))
    p + geom_line()
    

    I'll leave it to you to tidy up the axis labels, legend title etc.

    HTH

提交回复
热议问题