繁体   English   中英

facet_wrap的某些面板上的geom_rect

[英]geom_rect on some panels of a facet_wrap

我试图在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的数据子集geom_rect 但这给了我这个警告:

警告信息:在[<-.factor 。factor( *tmp* ,rng,value = 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)

在此输入图像描述

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

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) 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM