gpt4 book ai didi

R:使用时间序列数据与 'splinefun' 和 ggplot2 'stat_function'

转载 作者:行者123 更新时间:2023-12-04 10:10:47 28 4
gpt4 key购买 nike

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

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

这是我目前的情节:

enter image description here

这是一个reprex:

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

最佳答案

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

enter image description here

用 R 版本 3.6.2 测试

关于R:使用时间序列数据与 'splinefun' 和 ggplot2 'stat_function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61348794/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com