我想知道是否有一种“直接”方式将ggplot facet面板中回归线的斜率与该面板的背景颜色相关联(即,在大网格中从负斜率可视地分离正斜率)。
我理解如何在GGplots中添加回归线 - 正如Adding a regression line to a facet_grid with qplot in R
中详细解释的那样如果您之前已将此信息添加到原始数据框中,我也了解如何更改背景 - 如Conditionally change panel background with facet_grid?
所述但是 - 有没有办法在“geom_rect”公式中执行此操作,而无需例如单独运行回归,将它们绑定到原始数据帧,然后将其用作geom_rect()的变量?有没有办法让geom_rect()使用来自stat_smooth()的信息?
Wouter
早期问题的简单回归线图的好例子:
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)
答案 0 :(得分:4)
这不是一个解决方案,而是一种解决方法。但它似乎已经好了。您链接的两个帖子都包含解决方案的每个部分。 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
输出看起来像。我不确定这是否是您所期望的。严格地说,您确实计算了两次拟合值,但两次都用stat_smooth
隐式计算。就像我说的那样,它只是一种解决方法。