如何将scale_y_datetime与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,sd = 300),y = difftime(x,lag(x,1))
) %>% 
  filter(!is.na(y))  # First lag(x,1) is NA.

所以df是:

# A tibble: 9 x 2
  x                   y            
  <dttm>              <drtn>       
1 2020-08-01 11:42:19 31.60503 mins
2 2020-08-01 12:09:29 27.17099 mins
3 2020-08-01 12:50:43 41.23540 mins
4 2020-08-01 13:10:45 20.03007 mins
5 2020-08-01 13:42:00 31.26120 mins
6 2020-08-01 14:24:41 42.67504 mins
7 2020-08-01 14:44:43 20.02577 mins
8 2020-08-01 15:15:10 30.45446 mins
9 2020-08-01 15:40:41 25.51719 mins

我使用水平堆叠的条形图进行绘制:

gg = ggplot(df,aes(x = 1,y = y,fill = as.factor(x))) + 
  geom_bar(stat = "identity") + 
  coord_flip()

enter image description here

现在,我想在df$x的x轴上显示时间。但是,这失败了:

gg + scale_y_datetime()

错误

Error: Invalid input: time_trans works with objects of class POSIXct only

可能是因为df$xdifftime对象。我尝试了各种解决方案,但只能得到一个非常round回的解决方案:

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)

enter image description here

这需要知道您的日期范围的大小(此处为“分钟”-> / 60),并且您无法对时间戳进行任何四舍五入。有没有使用scale_y_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,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)

enter image description here