考虑此示例
library(lubridate)
library(tibble)
library(lattice)
dat <- tibble(mydate = c(ymd('2018-02-01'),
ymd('2018-02-02'),
ymd('2018-02-03'),
ymd('2018-02-04'),
ymd('2018-02-05')),
myx = c(1,2,3,4,5),
myz = c(2,3,2,3,1))
# A tibble: 5 x 3
mydate myx myz
<date> <dbl> <dbl>
1 2018-02-01 1 2
2 2018-02-02 2 3
3 2018-02-03 3 2
4 2018-02-04 4 3
5 2018-02-05 5 1
我知道我可以使用xyplot
轻松绘制两个时间序列
dat %>% xyplot(myx + myz ~ mydate, outer = TRUE, data = ., type = 'l',
layout = c(1,2))
我的问题是我还有一个包含感兴趣的日期的tibble
,并且我想在上面的图表中绘制这些日期的垂直线。
events <- tibble(mydate = c(ymd('2018-02-03'),
ymd('2018-02-05')))
我如何轻松做到这一点? 谢谢!
答案 0 :(得分:1)
1)面板功能使用这样的面板功能:
xyplot(myx + myz ~ mydate, dat, outer = TRUE, type = "l", layout = 1:2,
panel = function(...) {
panel.xyplot(...)
panel.abline(v = events$mydate)
})
2)层,或在gridExtra中使用层:
library(latticeExtra)
xyplot(myx + myz ~ mydate, dat, outer = TRUE, type = "l", layout = 1:2) +
layer(panel.abline(v = mydate), data = events)
2a)xyplot.zoo 请注意,可以使用zoo对其进行一些简化:
library(latticeExtra)
library(zoo)
z <- read.zoo(dat)
xyplot(z) + layer(panel.abline(v = mydate), data = events)
要将第一条垂直线仅添加到第一面板,将第二条垂直线添加到第二面板:
xyplot(z) +
layer(panel.abline(v = mydate[1]), data = events, packets = 1) +
layer(panel.abline(v = mydate[2]), data = events, packets = 2)
或
vline <- function(i) {
layer(panel.abline(v = events$mydate[i]), data = list(i = i), packets = i)
}
Reduce("+", init = xyplot(z), lapply(1:2, vline))