geom_rect在facet_wrap的某些面板上 [英] geom_rect on some panels of a facet_wrap
问题描述
我试图在我的 facet_wrap
图中的前三个面板上绘制阴影矩形。但是,当我使用 geom_rect
作业时,它会在每个面板上生成矩形。有没有办法选择只在前三个面板上获得矩形?
I am trying to get a shaded rectangle on the first three panels in my facet_wrap
plot. However, when I use geom_rect
for the job, it produces the rectangle on each of the panels. Is there a way to selectively get the rectangle only on the first three panels?
这是一些代码
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)
更新1:
我将代码更新为
Update 1:
I updated my code to
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)
请注意,我现在将传递给 geom_rect
的数据进行子集化。但是,这给了我这个警告:
Note that I am now subsetting the data that I am passing to geom_rect
. But this gives me this warning:
警告消息:在
[< - 。factor
(* tmp *
,rng,value = c(1L,1L,1L,
1L,1L,1L,:无效因子水平, / p>
Warning message: In
[<-.factor
(*tmp*
, rng, value = c(1L, 1L, 1L, 1L, 1L, 1L, : invalid factor level, NA generated
这是什么意思?
What does this mean?
推荐答案
这是一个解决方案,它使用 variable
创建一个新的数据框,然后利用 aes
中的回收来生成变量
中每个值的矩形坐标。
Here is a solution that creates a new data frame with variable
and then takes advantage of recycling in aes
to generate the rectangle coordinates for each value in 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)
这篇关于geom_rect在facet_wrap的某些面板上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!