rggplot2ggpubr

Stat-cor not working. Keeps telling me to "transform_date"


I am just trying to add correlation data to the ggplot I am making about daily temperature readings. Here is the code I am using currently and the error it gives me.

library(ggpubr)

S4TailGaugeDailyAvgPlot <-
  
ggplot(S4TailGaugeDailyAvgdf, aes(Date, NULL)) +
  geom_smooth(aes(x = Date, y = mean_temps4), alpha = 0.25) +
  geom_line(aes(x = Date, y = mean_temps4, color = "S4")) +
  
  geom_smooth(aes(x = Date, y = mean_temptailwater, colour = "Tailwater Gauge"), alpha = 0.25) +
  geom_line(aes(x = Date, y = mean_temptailwater, colour = "Tailwater Gauge")) +
  
  scale_colour_manual("",values = c("S4"="blue", "Tailwater Gauge"="red")) +
  theme(legend.position = "bottom") +
  xlab('Date') + ylab('Daily Average Temperature (Celcius)') +
  ggtitle("Daily Average Temperature
Site S4 vs Tailwater Gauge")

S4TailGaugeDailyAvgPlot + stat_cor(aes(mean_temps4, mean_temptailwater), method = "spearman")

S4TailGaugeDailyAvgPlot + stat_cor(aes(mean_temps4, mean_temptailwater), method = "spearman")
Error in `transformation$transform()`:
! `transform_date()` works with objects of class <Date> only
Run `rlang::last_trace()` to see where the error occurred.

Here is the data I am using.

dput(head(S4TailGaugeDailyAvgdf))
structure(list(Date = structure(c(19791, 19792, 19793, 19794, 
19795, 19796), class = "Date"), mean_temps4 = c(7.74298146565755, 
7.689453125, 7.8524668375651, 8.49865397135417, 8.65640228271484, 
8.60590494791666), mean_temptailwater = c(8.16875, 8.13695652173913, 
8.590625, 9.03854166666667, 9.00104166666667, 8.73645833333333
), mean_gaugeheighttailwater = c(70.8421875, 70.8433695652174, 
73.6369791666667, 76.0657291666667, 74.1148958333333, 71.3278125
)), row.names = c(NA, 6L), class = "data.frame")

I'm very confused why it is not working and what I am doing wrong. Any help much appreciated. Thanks.


Solution

  • I'm not sure why stat_cor is not playing well with your date scale. I would just annotate the plot yourself, e.g. like so:

    S4TailGaugeDailyAvgPlot + 
      annotate(
        geom = 'text', 
        x = as.Date('2024-03-10'), 
        y = 9, 
        label = paste(
          'R =', 
          with(S4TailGaugeDailyAvgdf, round(cor(mean_temps4, mean_temptailwater), 3))
        )
      )