R 如何将scale_y_datetime与difftime数据一起使用?

R 如何将scale_y_datetime与difftime数据一起使用?,r,datetime,ggplot2,axis-labels,posixct,R,Datetime,Ggplot2,Axis Labels,Posixct,有没有办法在累积持续时间的水平堆叠条形图中使用scale_y_datetime 我的数据结构如下: x1 = as.POSIXct("2020-08-01 12:00") x2 = as.POSIXct("2020-08-01 16:00") df = tibble::tibble( x = seq(dt_start, dt_end, length.out = 10) + rnorm(10, 0, sd = 300), y = difftime(

有没有办法在累积持续时间的水平堆叠条形图中使用scale_y_datetime

我的数据结构如下:

x1 = as.POSIXct("2020-08-01 12:00")
x2 = as.POSIXct("2020-08-01 16:00")
df = tibble::tibble(
  x = seq(dt_start, dt_end, length.out = 10) + rnorm(10, 0, sd = 300), 
  y = difftime(x, lag(x, 1))
) %>% 
  filter(!is.na(y))  # First lag(x, 1) is NA.
因此,df是:

现在我想在x轴上显示时间,单位为df$x。但是,这一点失败了:

gg + scale_y_datetime()
带着错误

Error: Invalid input: time_trans works with objects of class POSIXct only
可能是因为df$x是一个difftime对象。我尝试过各种解决方案,但只得到了一个非常迂回的解决方案:

x_pos = seq(min(df$x), max(df$x), length.out = 10)
x_label = format(x_pos, "%H:%M")
gg + scale_y_continuous(breaks = as.numeric(x_pos - min(df$x)) / 60, labels = x_label)

这需要知道你的日期范围在这里的范围是分钟->/60,而你的时间戳并没有很好的四舍五入。有没有一种方法可以使用scale\u y\u datetime?

我想我没有抓住为什么要使用时差的要点。。但我不是从你的问题中得到的

你不能接受这个吗

library(dplyr)
library(ggplot2)

# reproducible example
x1 <- Sys.time()
x2 <- Sys.time() + 1000
df <- tibble::tibble(x = seq(x1, x2, length.out = 10) + rnorm(10, 0, sd = 300))
df <- df %>% mutate(x1 = lag(x)) %>% filter(!is.na(x1))


# solution ?
ggplot(df) +
    geom_rect(aes(xmin = x1, xmax = x, ymin = 0, ymax = 1, fill = factor(x)), show.legend = FALSE)

没有x1,x2定义?@RonakShah谢谢你的捕获。现在可以复制了。
x_pos = seq(min(df$x), max(df$x), length.out = 10)
x_label = format(x_pos, "%H:%M")
gg + scale_y_continuous(breaks = as.numeric(x_pos - min(df$x)) / 60, labels = x_label)
library(dplyr)
library(ggplot2)

# reproducible example
x1 <- Sys.time()
x2 <- Sys.time() + 1000
df <- tibble::tibble(x = seq(x1, x2, length.out = 10) + rnorm(10, 0, sd = 300))
df <- df %>% mutate(x1 = lag(x)) %>% filter(!is.na(x1))


# solution ?
ggplot(df) +
    geom_rect(aes(xmin = x1, xmax = x, ymin = 0, ymax = 1, fill = factor(x)), show.legend = FALSE)