【发布时间】:2018-09-24 18:25:10
【问题描述】:
我正在创建一个时间表图来显示每个时间块中有多少事件。我已经从 lubridate 计算了所有这些信息,并且可以在 ggplot 上很好地绘制它。但我需要反转/翻转轴,以便顶部显示上午 8 点并下降到下午 5 点,而不是下午 5 点到上午 8 点。
这就是我的最终结果的 sn-p 目前的样子。只需要颠倒时间顺序就完美了。这从上午 8 点到下午 5 点和 M-F 延伸。
我尝试使用 scale_y_reverse 但这不起作用。
我看到了这篇文章,但我无法弄清楚如何在我的情况下使用它:Reverse datetime (POSIXct data) axis in ggplot
样本数据(使用 dput fn 创建):
df <- structure(list(ID = c(4108L, 4165L, 1504L, 2570L, 1523L, 2556L,
3224L, 1503L, 3220L, 837L), START_TIME = structure(c(1504267200,
1504281600, 1504258200, 1504278000, 1504263600, 1504256400, 1504258200,
1504274400, 1504258200, 1504256400), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), END_TIME = structure(c(1504270799, 1504285199,
1504263599, 1504281599, 1504268999, 1504259999, 1504263599, 1504279799,
1504263599, 1504259999), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
Day = structure(c(5L, 5L, 2L, 3L, 2L, 3L, 4L, 2L, 4L, 1L), .Label = c("M",
"T", "W", "R", "F"), class = "factor")), row.names = c(322L,
351L, 112L, 188L, 125L, 179L, 298L, 111L, 294L, 8L), class = "data.frame")
我的代码:
library(ggplot2)
library(scales)
ggplot(df) +
geom_rect(aes(xmin= 0, xmax= 2, ymin = START_TIME, ymax = END_TIME),
color = "#ffffff",
position="dodge") +
scale_y_datetime(date_breaks="1 hour", labels = date_format("%I:%M %p"), expand = expand_scale(.1)) +
theme_minimal() +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_blank(),
panel.grid = element_blank(),
panel.grid.major.y = element_line(color = "#cccccc"),
axis.title = element_blank()) +
facet_wrap(~Day, nrow=1)
【问题讨论】:
-
想知道您是否找到了一种简单的方法来做到这一点?我今天也在尝试做同样的事情。
-
不,我现在不得不把它放在次要位置并使用@dave2e的解决方案。
标签: r datetime ggplot2 lubridate