ggplotly and lubridate: Hoover shows seconds, not minutes

Viewed 107

I created a boxplot with ggplot with the following data.frame:

library(lubridate)
library(ggplot2)
library(ggplotly)

df <- data.frame(
  time = c("00:43:20", "00:44:30","00:45:40"),
  sex = c("m","m","m")
)

df$sex <- factor(df$sex)
df$time <- lubridate::hms(df$time)

Now I created my boxplot with ggplot

g <- ggplot(df) +
  geom_boxplot(aes(sex, time)) +
  scale_y_time()

Everything looks fine and now get interactive with ggploty():

plotly::ggplotly(g)

enter image description here

But when I hoover over the boxplot, I just see seconds, not the lubridate format. How can I manage to see the data as shown on the y-axis?

1 Answers

The problem is rather complex from what I understand. The main issue seems to be that lubridate stores times as periods. Therefore you get the seconds in plotly as in ggplot they are seconds as well, they just where converted on the scale by "scale_y_time".

From my understanding the work arround would be to convert the time value to a numeric value of minutes. Though this means a minutes will have 100sec after the comma/dot:

1st option with ggplot:

library(plotly)
library(ggplot)
library(lubridate)
# calculate time as minutes passed and get it as numeriic
mins <- as.numeric(lubridate::hms(df$time) - hms("00:00:00"))/60

df$sex <- factor(df$sex)
df$time <- mins 

g <- ggplot2::ggplot(df) +
       ggplot2::geom_boxplot(aes(sex, time)) 

plotly::ggplotly(g)

enter image description here

2nd option with plotly directly (only for the text data not sure if you could add sex F as x or if you need a second trace and some cosmetics need to be done also... anyhow ggplot gives practicalle the same result)

plotly::plot_ly(y = ~mins, type = "box")

enter image description here

Possibly there is a better solution - I just could not figure it out in the last 2 hours ;(

Related