这里有一个解决方案,它依赖于:(1)将时间轴分成5分钟宽的区间,(2)重建长格式数据,以及(3)利用
geom_bar(position="stack")
的堆叠能力。
dat = structure(list(Dest = c("KP", "KI", "ST"), Total = c(1L, 3L, 1L),
start = structure(c(1381730700, 1381731600, 1381732200),
class = c("POSIXct", "POSIXt"), tzone = ""),
end = structure(c(1381731600, 1381732500, 1381733100),
class = c("POSIXct", "POSIXt"), tzone = "")),
.Names = c("Dest", "Total", "start", "end"),
class = "data.frame", row.names = c(NA, -3L))
Time = as.POSIXct(vector())
Dest = vector("character", length=0)
Total = vector("integer", length=0)
for (i in seq(nrow(dat))) {
times = seq(from=dat[i, "start"], to=dat[i, "end"], by="5 min")
times = head(times, -1)
Time = c(Time, times)
Dest = c(Dest, rep(dat[i, "Dest"], length(times)))
Total= c(Total, rep(dat[i, "Total"], length(times)))
}
dat2 = data.frame(Time, Total, Dest)
library(ggplot2)
p = ggplot(dat2, aes(x=Time, y=Total, fill=Dest)) +
geom_bar(stat="identity", position="stack", width=300, color="grey30")
ggsave("plot.png", plot=p, width=10, height=4.5, dpi=120)
注意事项:
- 您可以通过更改
seq(..., by=
参数来改变bin的宽度。请参阅?seq.POSIXt
。
- 您可能希望将
start
和end
时间四舍五入到最接近x分钟,以便简化分箱过程。
geom_bar(..., width=300)
之所以有效是因为5分钟内有300秒。根据需要进行调整。
- x轴上的刻度标记位于条形图的中心,但实际上应用于条形图的左边缘。请像@agstudy所示使用
scale_x_datetime(breaks=
进行调整。