facet_wrap的某些面板上的geom_rect

时间:2014-03-06 16:32:21

标签: r ggplot2

我正在尝试在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) 

更新1:

我将代码更新为

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的数据进行子集化。但这给了我这个警告:

  

警告讯息:在[<-.factor*tmp*,rng,值= c(1L,1L,1L,   1L,1L,1L,:无效因子水平,NA生成

这是什么意思?

2 个答案:

答案 0 :(得分:7)

以下是使用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)

enter image description here

答案 1 :(得分:7)

有一种非常简单的方法可以做到这一点:

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) 

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