【问题标题】:ggplotly and lubridate: Hoover shows seconds, not minutesggplotly 和 lubridate:胡佛显示秒,而不是分钟
【发布时间】:2021-02-22 19:34:57
【问题描述】:

我用 ggplot 用以下 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)

现在我用 ggplot 创建了箱线图

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

一切看起来都很好,现在可以与ggploty()互动:

plotly::ggplotly(g)

但是当我将鼠标悬停在箱线图上时,我只看到秒数,而不是 lubridate 格式。 如何查看 y 轴上显示的数据?

【问题讨论】:

标签: r ggplot2 plotly lubridate ggplotly


【解决方案1】:

据我了解,这个问题相当复杂。主要问题似乎是 lubridate 将时间存储为句点。因此,您可以像在 ggplot 中一样在 plotly 中获得秒数,它们也是秒数,它们只是按“scale_y_time”按比例转换。

据我了解,解决方法是将时间值转换为分钟的数值。虽然这意味着逗号/点之后的一分钟将有 100 秒:

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)

直接使用 plotly 的第二个选项(仅适用于文本数据,不确定是否可以将性别 F 添加为 x 或者是否需要第二次跟踪并且还需要完成一些化妆品......无论如何 ggplot 给出了相同的结果)

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

可能有更好的解决方案 - 我只是在过去 2 小时内无法弄清楚;(

【讨论】:

  • 谢谢你的想法..我会试试的!
猜你喜欢
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
相关资源
最近更新 更多