关于 r:Statistical Model Representation with ggplot2 | 珊瑚贝

Statistical Model Representation with ggplot2


我会用一个研究案例来问我的问题,然后我会让我的问题更笼统。

让我们先导入一些库并创建一些数据:

1
2
3
4
5
require(visreg)
require(ggplot2)    
y = c(rnorm(40,10,1), rnorm(20,11,1), rnorm(5,12,1))
x=c(rep(1,40), rep(2,20), rep(3,5))
dt=data.frame(x=x, y=y)

并在 x 上运行 y 的线性回归,并使用 ggplot2

绘制数据和模型

1
2
m1 = lm(y~x, data=dt)
ggplot(dt, aes(x,y)) + geom_point() + geom_smooth(formula = y~x, method=”anova”, data=dt)

enter

现在我想将我的 x 变量视为名义变量。所以我稍微改变我的数据并运行以下模型。

1
2
3
4
y = c(rnorm(40,10,1), rnorm(20,11,1), rnorm(5,12,1))
x=factor(c(rep(1,40), rep(2,20), rep(3,5))) # this line has changed!
dt=data.frame(x=x, y=y)
m2 = lm(y~x, data=dt)

如何用 ggplot2 绘制这个模型 m2?更全局地说,我怎样才能直接告诉 ggplot 考虑对象 m2 以创建模型的表示?

我的目标是使用 visreg 包

可以完成的事情

1
visreg(m2)

enter

那么,ggplot 有没有类似 visreg 的解决方案?类似

1
ggplot(..,aes(..)) + super_geom_smooth(model = m2)

这与@rnso 的想法没有太大区别。 geom_jitter() 增加了更多的味道。我还更改了中值条的颜色。希望对你有帮助!

1
2
3
4
5
6
ggplot(data = m2$model, aes(x = x, y = y)) +
geom_boxplot(fill =”gray90″) +
geom_jitter()  +
theme_bw() +
stat_summary(geom =”crossbar”, width = 0.65, fatten = 0, color =”blue”,
fun.data = function(x){return(c(y=median(x), ymin=median(x), ymax=median(x)))})

enter

  • 谢谢!我意识到看到您的回答,我的问题非常不清楚。对于那个很抱歉。我发布了另一个更符合我在这里寻找的问题的问题。


仅供参考,visreg 现在可以输出 gg 对象:

1
visreg(m2, gg=TRUE)

enter


以下使用箱线图与您想要的图表非常相似:

1
ggplot(dt, aes(x,y))+ geom_boxplot(aes(group=x), alpha=0.5)+ geom_jitter()


enter

  • 也许这样的事情也可以。 ggplot(data = m2$model, aes(x = x, y = y)) + geom_boxplot() + geom_jitter()
  • @ jazzurro:您的解决方案有效。将其发布为答案。
  • 谢谢你,伙计。完毕。
  • 如果添加 geom_jitter(),您可能想要删除 geom_point()。您现在正在两次绘制相同的点。





来源:https://www.codenong.com/26028681/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9402.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?