R GGplot2中面板背景的条件格式

R GGplot2中面板背景的条件格式,r,ggplot2,regression,R,Ggplot2,Regression,我想知道是否有一种“直接”的方式将ggplot镶嵌面面板中回归线的斜率与该面板的背景色联系起来(即在大网格中从视觉上区分正斜率和负斜率) 我知道如何在GGplots中添加回归线,这在 如果您之前已将此信息添加到原始数据帧中,我也了解如何更改背景-如上所述 但是-是否有一种方法可以在“geom_rect”公式中实现这一点,而不必单独运行回归,将它们绑定到原始数据帧,然后将其用作geom_rect()的变量?geom_rect()是否有办法使用stat_smooth()中的信息 沃特 前面问题中简单

我想知道是否有一种“直接”的方式将ggplot镶嵌面面板中回归线的斜率与该面板的背景色联系起来(即在大网格中从视觉上区分正斜率和负斜率)

我知道如何在GGplots中添加回归线,这在

如果您之前已将此信息添加到原始数据帧中,我也了解如何更改背景-如上所述

但是-是否有一种方法可以在“geom_rect”公式中实现这一点,而不必单独运行回归,将它们绑定到原始数据帧,然后将其用作geom_rect()的变量?geom_rect()是否有办法使用stat_smooth()中的信息

沃特

前面问题中简单回归线图的好例子:

library(ggplot2)
x <- rnorm(100)
y <-  + .7*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

ggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+stat_smooth(method="lm",se=FALSE)
库(ggplot2)

这不完全是一个解决方案,而是一个解决办法。但结果似乎不错。您链接到的两个帖子都包含解决方案的每个部分。告诉您如何从
stat\u smooth
提取拟合值。说明如何使用
geom\u 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
#生成数据:使用set.seed实现再现性
#我还将乘法常数改为0.1,以便
#至少有一个负斜率。
需要(ggplot2)
种子(12)

x One在说这句话时总是惹麻烦,但我要说不,你不能做你所描述的。实现此效果的方法是将坡度添加为变量,然后将该变量映射到
geom\u rect
中的背景色。如果不在ggplot外部建模,尝试此操作的一个问题是,您不知道坡度是否在任何实际意义上与零不同(除了微不足道的标称坡度)。下面的例子中,你会遇到一个主要基于统计噪声的着色风险;还要感谢Matt和Joran的观点。最后一个问题——我想我明白了状态平滑(aes(装备=适合