如何制作ggplot情节geom_smooth(method =“lm”),但前提是它符合某些标准?例如,如果我只想绘制线条,如果斜率具有统计显着性(即lm
拟合中的 p 小于0.01)。
编辑:更新为涉及方面的更复杂的示例。我没有从头开始生成数据,而是修改了diamonds
数据集。
library(ggplot2)
library(data.table)
data(diamonds)
set.seed(777)
d <- data.table(diamonds)
d[color %in% c("D","E"), c("x","y") := list(x + runif(1000, -5, 5),
y + runif(1000, -5, 5))]
plt <- ggplot(d) + aes(x=x, y=y, color=color) +
geom_point() + facet_grid(clarity ~ cut, scales="free")
plt + geom_smooth(method="lm")
我想要的是绘制除了那些没有统计上显着斜率(即D和E)的线以外的所有线的方法。
答案 0 :(得分:6)
您可以按组计算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")