应用透明背景以使用ggplot根据x值划分绘图区域

apply transparent background to divide plot area based on x values using ggplot

I would appreciate any help to apply the transparent background colours below to divide into two parts the plot area based on x-values as illustrated in the plot below (vertical division).

这是我的示例数据和代码:

mtcars$cyl <- as.factor(mtcars$cyl)
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl)) +
  geom_point() + 
  theme(legend.position="none")+
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)

这是我想复制的情节,图例说明了我想实施的变化:

提前致谢。

我想你想要这样的东西。您必须指定组并在 geom_ribbon 中填写该组,然后根据需要设置 yminymax

library(tidyverse)
    mtcars$group <- ifelse(mtcars$wt <= 3.5, "<= 3.5", "> 3.5")
mtcars <- arrange(mtcars, wt)
mtcars$group2 <- rleid(mtcars$group)
mtcars_plot <- head(do.call(rbind, by(mtcars, mtcars$group2, rbind, NA)), -1)
mtcars_plot[,c("group2","group")] <- lapply(mtcars_plot[,c("group2","group")], na.locf)
mtcars_plot[] <- lapply(mtcars_plot, na.locf, fromLast = TRUE)

ggplot(mtcars_plot, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(aes(), method=lm, se=F, fullrange=TRUE) +
  geom_ribbon(aes(ymin = mpg *.75, ymax = mpg * 1.25, fill = group), alpha = .25) +
  labs(fill = "Weight Class")

编辑:

要使用 geom_ribbon 映射置信区间,您必须事先使用 lmpredict.

计算它们
mtmodel <- lm(mpg ~ wt, data = mtcars)
mtcars$Low <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,2]
mtcars$High <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,3]

接着前面的代码修改mtcars。然后用计算出的界限作图。

ggplot(mtcars_plot, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(aes(), method=lm, se=F, fullrange=TRUE) +
  geom_ribbon(aes(ymin = Low, ymax = High, fill = group), alpha = .25) +
  labs(fill = "Weight Class") +
  scale_fill_manual(values = c("red", "orange"), name = "fill")