您可以按组计算 p 值,然后在 geom_smooth 中进行子集计算(根据评论者):
# Determine p-values of regression
p.vals = sapply(unique(d$z), function(i) {
coef(summary(lm(y ~ x, data=d[z==i, ])))[2,4]
})
plt <- ggplot(d) + aes(x=x, y=y, color=z) + geom_point()
# Select only values of z for which regression p-value is < 0.05
plt + geom_smooth(data=d[d$z %in% names(p.vals)[p.vals < 0.05],],
aes(x, y, colour=z), method='lm')
更新:根据您的评论,试试这个,例如:
p1 = ggplot(mtcars, aes(wt, mpg)) +
geom_point() + facet_grid(am ~ carb)
dat = data.frame(x=1:5, y=26:30, carb=1:5)
p1 + geom_point(data=dat, aes(x,y), colour="red", size=5)
请注意,由于dat 没有am 列,ggplot 只是在dat 中为am 的每个值绘制相同的值。当然,您可以为am 添加值,并逐面控制绘制的内容。
更新 2: 我认为这将处理分面情况。但是请注意,大多数回归的 p 值都小于 0.05,这可能是因为当您拥有大量数据时,即使是很小的系数也会具有统计显着性。
## Create a list holing the p-values for regressions on each
## combination of color, cut, and clarity
pvals = lapply(levels(d$color), function(i) {
lapply(levels(d$cut), function(j) {
lapply(levels(d$clarity), function(k) {
if(nrow(d[color==i & cut==j & clarity==k, ]) > 1) {
data.frame(color=i, cut=j, clarity=k,
p.val=coef(summary(lm(y ~ x, data = d[color==i & cut==j & clarity==k, ])))[2,4])
}
})
})
})
# Flatten pvals to a single list level
pvals = unlist(unlist(pvals, recursive=FALSE), recursive=FALSE)
# Turn pvals into a data frame
pvals = do.call(rbind, pvals)
# Keep only rows with p.val < 0.05
pvals = pvals[pvals$p.val < 0.05, ]
plt <- ggplot(d) + aes(x=x, y=y, color=color) +
geom_point() + facet_grid(clarity ~ cut, scales="free")
# Create a subset of data frame d containing only combinations of
# color, cut, and clarity for which we want to plot regression lines
# (you could subset right in the call to geom_smooth, but I thought this would be more clear)
d.subset = d[color %in% pvals$color &
cut %in% pvals$cut &
clarity %in% pvals$clarity, ]
# Plot regression lines only for groups in d.subset
plt + geom_smooth(data=d.subset, method="lm")