2

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?

J_F
  • 9,956
  • 2
  • 31
  • 55
  • 1
    I'm not sure but try to look here: https://stackoverflow.com/questions/42413282/displaying-plotly-histogram-time-in-hhmmss – DJV Nov 10 '20 at 20:38
  • @DJV Thanks for the link but I think there are just modifications on the x-axis, not on the appearance when hoover over it. – J_F Nov 10 '20 at 21:02
  • could you create a second `character` time variable and then edit the hover information of the boxplot? https://stackoverflow.com/questions/47518245/plotly-annotate-outliers-with-sample-names-in-boxplot not sure it would work, but might be a hacky solution – user63230 Nov 11 '20 at 08:38

1 Answers1

2

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 ;(

DPH
  • 4,244
  • 1
  • 8
  • 18