我希望将下面的透明背景色应用于 根据x值将绘图区域分为两部分,如下图所示(垂直分割)。
以下是我的示例数据和代码:
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)
这是我要复制的情节,图例说明了我要实现的更改:
谢谢。
答案 0 :(得分:1)
我认为您想要这样的东西。您必须指定一组并在c
中填充该组,并根据需要设置select
e.FirstName,
e.LastName,
o.OrderDate as Date,
c.CompanyName as CustomerCompany
from
Employees e
join Orders o on o.EmployeeID = e.EmployeeID
join Customers c on c.CustomerID = o.CustomerID
和geom_ribbon
。
ymin
修改:
要使用ymax
映射置信区间,您必须事先使用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
计算它们。
lm
后面的代码用于修改predict
。然后绘制计算出的边界。
mtmodel <- lm(mpg ~ wt, data = mtcars)
mtcars$Low <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,2]
mtcars$High <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,3]