首页 文章

在同一图表上使用ggplot2将两个变量绘制为线条

提问于
浏览
244

一个非常新的问题,但是说我有这样的数据:

test_data <-
  data.frame(
    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=100)
  )

如何在同一图表上绘制时间序列 var0var1 ,在x轴上使用 date ,使用 ggplot2 ?如果你制作 var0var1 不同的颜色,可以包括一个传奇!

我确信这很简单,但我找不到任何例子 .

4 回答

  • 305

    一般方法是将数据转换为长格式(使用包 reshapereshape2 中的 melt() )或 tidyr 包中的 gather()

    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

  • 308

    使用您的数据:

    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))
    

    我创建了一个堆叠版本,这是 ggplot() 想要使用的:

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

    在这种情况下,生成 stacked 非常简单,因为我们只需要进行一些操作,但如果你有一个更复杂的实际数据集来操作, reshape()reshapereshape2 可能会很有用 .

    一旦数据处于这种堆叠形式,它只需要一个简单的 ggplot() 调用来生成你想要的所有额外的绘图(更高级绘图包如 latticeggplot2 非常有用的一个原因):

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

    我会留给你整理轴标签,图例 Headers 等 .

    HTH

  • 12

    对于少量变量,您可以自己手动构建绘图:

    ggplot(test_data, aes(date)) + 
      geom_line(aes(y = var0, colour = "var0")) + 
      geom_line(aes(y = var1, colour = "var1"))
    
  • 24

    对于ggplot2,您需要数据为"tall"格式而不是"wide" . "wide"表示每行观察一次,每个变量作为不同的列(就像你现在一样) . 您需要将其转换为"tall"格式,其中有一列告诉您变量的名称,另一列告诉您变量的值 . 从宽到高的过程通常称为"melting" . 您可以使用 tidyr::gather 来融化数据框:

    library(ggplot2)
    library(tidyr)
    
    test_data <-
      data.frame(
        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=100)
      )
    test_data %>%
        gather(key,value, var0, var1) %>%
        ggplot(aes(x=date, y=value, colour=key)) +
        geom_line()
    

    只是为了清楚 ggplot ggplot 在通过 gather 进行管道输送后正在消耗,如下所示:

    date        key     value
    2002-01-01  var0    100.00000
    2002-02-01  var0    115.16388 
    ...
    2007-11-01  var1    114.86302
    2007-12-01  var1    119.30996
    

相关问题