Search code examples
rggplot2plotlyggplotly

ggplotly() does not put date on x-axis


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)

Solution

  • 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.