【问题标题】:R: Using time series data with 'splinefun' and ggplot2 'stat_function'R:使用带有“splinefun”和ggplot2“stat_function”的时间序列数据
【发布时间】:2020-08-04 12:14:17
【问题描述】:

我有时间序列数据,每个时间都有一个观察结果。我通过 R 的splinefun 运行它来为观察创建一个样条函数。我想使用stat_functionggplot2 中绘制这个样条函数。我希望我的绘图将日期/时间作为 X 轴,而不是按行索引的 X 轴。可以说我已经尝试了很多事情,从编辑 splinefun 的结果(尝试使其与 as.POSIXct 一起使用),到在 ggplot 命令中加入不同的美学。

如何获取 X 轴上的日期/时间?

这是我目前的情节:

这是一个代表:

library(ggplot2)

DateTime <- seq.POSIXt(from = as.POSIXct('2020-01-10'),
                       to = as.POSIXct('2020-01-12'),
                       by = '1 hour')
set.seed(1)
y <- runif(length(DateTime), min = 0.5) * cos(as.numeric(DateTime))

df <- data.frame(DateTime = DateTime, 
                 x = seq(1:length(DateTime)),
                 y = y)

myspline <- splinefun(df$x, df$y)

ggplot(mapping = aes(x=1:nrow(df))) +
    stat_function(fun = myspline, size = 1, args = list(deriv = 0))

【问题讨论】:

    标签: r function ggplot2 spline stat


    【解决方案1】:

    splinefun 函数对我来说似乎适用于 POSIXct 值

    set.seed(1)
    
    df <- transform(data.frame(DateTime = seq.POSIXt(from = as.POSIXct('2020-01-10'),
                                           to = as.POSIXct('2020-01-12'),
                                           by = '1 hour')),
      y=runif(length(DateTime), min = 0.5) * cos(as.numeric(DateTime)))
    
    
    library(ggplot2)
    myspline <- splinefun(df$DateTime, df$y)
    
    ggplot(df, mapping = aes(x=DateTime)) +
      stat_function(fun = myspline, size = 1, args = list(deriv = 0))
    

    使用 R 版本 3.6.2 测试

    【讨论】:

    • 看起来这只有在 DateTime 仍然是全局环境中的对象时才有效。在我的非代表代码中,我没有带有 DateTime 的单独向量。换句话说,我假设 ggplot 中的映射命令以某种方式从 stat_function 中提取 DateTime ......但是它从全局环境中提取它?
    • 好吧,你似乎从来没有将你的 data.frame 传递给 ggplot。我已经更新到一个没有全局变量的示例,并正确地将 data.frame 传递给 ggplot 进行绘图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    相关资源
    最近更新 更多