이 정확히 솔루션 아니지만, 해결 방법. 그러나 그것은 좋게 나온 것으로 보인다. 링크 된 게시물에는 모두 솔루션의 각 부분이 있습니다. James' solution here은 맞는 값을 stat_smooth
에서 추출하는 방법을 알려줍니다. Joran's solution here은 geom_rect
을 사용하여 백그라운드를 작성하는 방법을 알려줍니다.
# generating data: Usage of set.seed for reproducibility
# also I changed the multiplication constant to 0.1 to have
# at least one negative slope.
require(ggplot2)
set.seed(12)
x <- rnorm(100)
y <- + .1*x + rnorm(100)
f1 <- as.factor(c(rep("A",50),rep("B",50)))
f2 <- as.factor(rep(c(rep("C",25),rep("D",25)),2))
df <- data.frame(cbind(x,y))
df$f1 <- f1
df$f2 <- f2
# first generate your plot in this manner and run it
# from James' post, the part outfit=fit<<-..y.. will store
# the output of fitted values in "fit"
g <- ggplot(df,aes(x=x,y=y)) + geom_point()+facet_grid(f1~f2)
g <- g + stat_smooth(aes(outfit=fit<<-..y..), method="lm",se=FALSE)
# now run g to generate "fit"
g
# now extract the slope for each facet and
# construct the data.frame for geom_rect (as per Joran's post)
# Edit: Just to add more info about "fit". By default it contains
# 80 values per facet. Hence the 80*4 = 320
slopes <- fit[seq(2, 320, by = 80)] - fit[seq(1, 320, by = 80)]
tp <- unique(df[, c('f1', 'f2')])
tp <- transform(tp, slopes=slopes, x=1, y=1)
tp$pos_neg <- ifelse(slopes > 0, 1, 0)
tp$pos_neg <- factor(tp$pos_neg)
# now plot again (but with geom_rect)
g <- ggplot(df,aes(x=x,y=y))
g <- g + geom_rect(data = tp, aes(fill = pos_neg), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 0.5)
g <- g + geom_point() + facet_grid(f1~f2) + stat_smooth(method = "lm",se = FALSE)
g
출력은 입니다. 나는 이것이 당신이 생각하는 것이지 확실치 않습니다. 엄밀히 말해서, 당신은 fitted 값을 두 번 계산하지만, 두 번 계산하면 암시 적으로 stat_smooth
으로 계산됩니다. 내가 말했듯이, 그것의 단지 주위.
이 말을 할 때 항상 사람이 문제를 제기하지만, 나는 아니오라고 말하면서 설명하는 것을 할 수 없습니다. 이 효과를 얻는 방법은 슬로프를 변수로 추가 한 다음 해당 변수를'geom_rect'에서 배경색으로 매핑하는 것입니다. – joran
ggplot 밖에서 모델링하지 않고이 문제를 시도하는 한 가지 문제는 기울기가 실제 의미에서 0과 실제로 다른지를 알 수 없다는 것입니다 (사소한 명목상의 것을 제외하고). 아래 예 에서처럼 주로 통계적 노이즈를 기반으로 색칠 위험이 있습니다. – MattBagg