【发布时间】:2020-09-02 08:02:05
【问题描述】:
有没有办法在累积持续时间的水平堆叠条形图中使用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 是:
# 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()
现在我想在 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_y_datetime()?
【问题讨论】:
-
未定义
x1、x2? -
@RonakShah 感谢您的关注。现在可以重现了。
标签: r datetime ggplot2 axis-labels posixct