我试图在我的facet_wrap情节中的前三个面板上得到一个阴影矩形.但是,当我geom_rect用于作业时,它会在每个面板上生成矩形.有没有办法只在前三个面板上选择性地获取矩形?
这是一些代码
dfTemp = data.frame(value = rnorm(100*4), variable = sort(rep(1:4, 100)),
date = rep(seq.Date(
from = as.Date('2011-01-01', format = '%Y-%m-%d'),
length.out = 100,
by = 'day'), 4))
ggplot(dfTemp) +
geom_rect(aes(xmin = as.Date('2011-02-01', format = '%Y-%m-%d'),
xmax = as.Date('2011-03-01', format = '%Y-%m-%d'),
ymin = -Inf,
ymax = Inf), alpha = 0.2, fill = 'grey') +
geom_line(aes(x = date, y = value, group = variable, color = factor(variable))) +
facet_wrap(~variable , scale = 'free', ncol = 1)
Run Code Online (Sandbox Code Playgroud)
我将我的代码更新为
dfTemp = data.frame(value = rnorm(100*4), variable = sort(rep(1:4, 100)),
date = rep(seq.Date(
from = as.Date('2011-01-01', format = '%Y-%m-%d'),
length.out = 100,
by = 'day'), 4))
ggplot(dfTemp) +
geom_rect(data = dfTemp[dfTemp$variable %in% c(2, 3),],
aes(xmin = as.Date('2011-02-01', format = '%Y-%m-%d'),
xmax = as.Date('2011-03-01', format = '%Y-%m-%d'),
ymin = -Inf,
ymax = Inf), alpha = 0.2, fill = 'grey') +
geom_line(aes(x = date, y = value, group = variable, color = factor(variable))) +
facet_wrap(~variable , scale = 'free', ncol = 1)
Run Code Online (Sandbox Code Playgroud)
请注意,我现在正在对我传递给的数据进行子集化geom_rect.但这给了我这个警告:
警告消息:在
[<-.factor(*tmp*,rng,值= c(1L,1L,1L,1L,1L,1L,:无效因子级别,生成NA)
这是什么意思?
这是一个创建新数据框的解决方案,variable然后利用回收aes来生成每个值的矩形坐标variable.
ggplot(dfTemp) +
geom_rect(
data=data.frame(variable=factor(1:3)),
aes(xmin=as.Date('2011-02-01'), xmax=as.Date('2011-03-01'), ymin=-Inf, ymax=Inf),
alpha = 0.5, fill = 'grey') +
geom_line(aes(x = date, y = value, group = variable, color = factor(variable))) +
facet_wrap(~variable , scale = 'free', ncol = 2)
Run Code Online (Sandbox Code Playgroud)

有一种非常简单的方法可以做到这一点:
library(ggplot2)
library(plyr) # for .(...)
ggplot(dfTemp) +
geom_rect(subset= .(variable<4),aes(xmin = as.Date('2011-02-01', format = '%Y-%m-%d'),
xmax = as.Date('2011-03-01', format = '%Y-%m-%d'),
ymin = -Inf,
ymax = Inf), alpha = 0.2, fill = 'grey') +
geom_line(aes(x = date, y = value, group = variable, color = factor(variable))) +
facet_wrap(~variable , scale = 'free', ncol = 1)
Run Code Online (Sandbox Code Playgroud)

与原始代码的唯一区别是添加subset=.(variable<4)到调用geom_rect(...).