gpt4 book ai didi

r - 在facet_wrap的某些面板上的geom_rect

转载 作者:行者123 更新时间:2023-12-04 10:07:29 26 4
gpt4 key购买 nike

我正在尝试在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的数据设置为子集。但这给了我这个警告:

Warning message: In [<-.factor(*tmp*, rng, value = c(1L, 1L, 1L, 1L, 1L, 1L, : invalid factor level, NA generated



这是什么意思?

最佳答案

这是一个使用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)

关于r - 在facet_wrap的某些面板上的geom_rect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22230376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com