Enes
Enes

Reputation: 149

Plotly or geom_smooth get lost date format?

I have multiple time-series plots. An example plot and code can be found below. I construct the plot using ggplot2 and make it interactive using ggplotly().

However, date format on the smoothed curve get lost. Interactive chart shows date as some numeric values.

How can I fix the problem?

Thank you very much

enter image description here

structure(list(Date = structure(c(15736, 15764, 15795, 15825, 
15856, 15886), class = "Date"), CLI = c(99.93, 100.3, 100.96, 
100.71, 100.62, 101.15)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))


plot5 <- df %>% 
  ggplot(aes(x = Date, y = CLI))+
  geom_line(size = 0.5, alpha = 0.75, show.legend = FALSE, color = "steelblue4")+
  scale_x_date(date_breaks = "6 month", date_labels =  "%m/%y")+
  theme_pander()+
  geom_line(stat='smooth', method = "glm", alpha=0.5, color = "firebrick2", formula = y ~ poly(x, 5))+
  geom_ribbon(stat='smooth',method = "glm", se=TRUE,formula = y ~ poly(x, 5), alpha=0.01)+
  labs(x = "Date",
       y = "Composite Leading Indicator")
ggplotly(plot5)

Upvotes: 0

Views: 306

Answers (1)

stefan
stefan

Reputation: 124148

Adapting my answer on this post to your case one option to get the date format in the tooltip would be to make use of the text aesthetic to manually create the tooltip and convert the numbers to proper dates like so:

plot <- df %>%
  ggplot(aes(x = Date, y = CLI)) +
  geom_line(size = 0.5, alpha = 0.75, show.legend = FALSE, color = "steelblue4") +
  scale_x_date(date_labels = "%m/%y") +
  # theme_pander()+
  geom_line(aes(text = paste(
    "date: ", as.Date(..x.., origin = "1970-01-01"), "<br>",
    "y:", ..y..
  )), stat = "smooth", method = "glm", alpha = 0.5, color = "firebrick2", formula = y ~ poly(x, 5)) +
  geom_ribbon(stat = "smooth", method = "glm", se = TRUE, formula = y ~ poly(x, 5), alpha = 0.01) +
  labs(
    x = "Date",
    y = "Composite Leading Indicator"
  )
ggplotly(plot, tooltip = c("text"))

enter image description here

Upvotes: 1

Related Questions