4

I have a plot that needs to be interactive, so I'm trying to plot it using the ggplotly() function. However, the x-axis gets values starting from 18k (days since 1970-01-01) instead of dates. I cannot use the normal plotly() function due to the plot being too complicated with different geoms that are supported by ggplotly() but not supported by plotly(). How could I get the dates on the x-axis?

library(ggplot2)
library(plotly)

data <- data.frame(x = runif(10) + 1:10,
                   date = seq.Date(as.Date("2019-07-01"),
                                   as.Date("2020-04-01"),
                                   by = "months"))

p <- ggplot(data, aes(x = date, y = x)) +
      geom_line()

ggplotly(p)
kkz
  • 306
  • 1
  • 8
  • You can add and addition layer `scale_x_date(date_labels = "%Y/%m/%d")` or whatever date format you want to `p` – paqmo Apr 02 '20 at 19:07

1 Answers1

3

Use a scaling function

You can add a x scaling function to your plot, like this:

library(ggplot2)
library(plotly)
data <- data.frame(x = runif(10) + 1:10,
                   date = seq.Date(as.Date("2019-07-01"),
                                   as.Date("2020-04-01"),
                                   by = "months"))

p <- ggplot(data, aes(x = date, y = x)) +
  geom_line() +
  scale_x_date(date_labels = "%Y/%m/%d")
ggplotly(p) 

Here's the output:

enter image description here

Hope this helps.

Louis
  • 3,592
  • 2
  • 10
  • 18