如何使用stat_smooth在两因子图上显示一行? [英] How can I use stat_smooth to show one line, on a two factor figure?
问题描述
我有这样一个data.frame:
I have a data.frame as such:
df <- data.frame(a = runif(1000), b = runif(1000), c = runif(1000), d = sample(c("yes", "no"), 1000, replace=TRUE))
我进行了逻辑回归:
lm <- glm(data = df, factor(d) ~ a + b + c, family = binomial)
产生了预测的概率:
df$pred <- predict(lm, type = "response")
并希望用 a
和 b
的抖动图, d
的颜色填充和平滑线来绘制结果图形(使用geom_smooth)仅用于 a
对 d
And would like to graph the result with both a jitter plot for a
and b
, a color fill for d
and a smooth line (using geom_smooth) for simply the effect of a
on d
我已经尝试过了:
ggplot(data = df , aes(x=a, y = b, color = factor(d))) + geom_jitter() +
geom_smooth(data = df, aes(x=a, y = pred))
但是它没有产生我想要的东西.我想要的是这一行:
But it's not producing what I would like. What I would like is this line:
ggplot(data = df , aes(x=a, y = pred)) + geom_smooth()
覆盖于此:
ggplot(data = df , aes(x=a, y = b, color = factor(d))) + geom_jitter()
我们将不胜感激.
推荐答案
这可以解决问题,现在不再按因素将其分组:
This does the trick, now it doesn't group it per factor anymore:
ggplot(data = df ) +
geom_point(aes(x=a, y = b, color = factor(d))) +
geom_smooth(aes(x=a, y = pred))
您现在可以在指定数据的位置制作一个ggplot.在此之上,添加一个包含点(a和b)的图层,并在该几何平滑线的顶部.
You now make a ggplot where you specify the data. On top of that you add a layer with points (a and b) and on top of that the geom smooth line.
但是请确保您同时查看了两个图的y轴.在您的geom_smooth()图中,您可以看到漂亮的S形曲线.但是,Y轴范围是0.51至0.47.
But make sure that you also have a look at the y-axis of both plots. In your geom_smooth() plot you see the nice s-shape curve. However, the Y-axis range is from 0.51 to 0.47.
如果我们再以极限为0和1来查看您的总图,则您的直线看起来几乎是笔直的,这仅仅是由于极限.
If we then look at your total plot with limits of 0 and 1. Your line looks almost straight which is just because of the limits.
这篇关于如何使用stat_smooth在两因子图上显示一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!