2
votes

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:

enter image description here

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

1 Answers

2
votes

The splinefun function seems to work just fine with POSIXct values for me

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

Tested with R version 3.6.2