I have time series data with one observation at each respective time. I run it through R's splinefun
to create a spline function for the observations. I would like to plot this spline function in ggplot2
using stat_function
. I would like for my plot to have date/time as the X axis, instead of the indexed-by-row X axis. Suffice it to say that I've tried many things, from editing the result of splinefun
(to try to make it work with as.POSIXct), to throwing different aesthetics at the ggplot command.
How do I get the dates/times on the X-axis?
Here is my current plot:
Here is a 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))