2014-09-25 44 views
0

我會用一個研究案例來問我的問題,然後我會提出更一般的問題。用ggplot2統計模型表示法


讓我們先來進口一些圖書館,並創建一些數據:

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

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

enter image description here模型

現在我w我想把我的x變量看作一個名義變量。所以我稍微改變我的數據並運行以下模型。

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) 

我該如何繪製這個模型m2與ggplot2?更全球的我怎麼能直接告訴ggplot考慮對象m2爲了創建模型的表示?

我做的目的是可以使用visreg

visreg(m2) 

enter image description here

所以要做的事情樣,有沒有ggplot任何visreg樣的解決方案?像

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

回答

2

這是不是來自@ rnso的想法非常不同。 geom_jitter()增添了更多的味道。我也改變了中位數的顏色。希望這可以幫助你!

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 image description here

+0

謝謝!我意識到看到你的回答,我的問題很不清楚。對於那個很抱歉。我發佈了另一個問題,更符合我所尋找的[這裏](http://stackoverflow.com/questions/26029608/directly-plot-a-statistical-model-with-ggplots)。 – 2014-09-25 02:37:53

1

使用箱線圖下面是非常相似,你想要的圖形:

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

enter image description here

+0

也許這樣的事情會做太多。 'ggplot(data = m2 $ model,aes(x = x,y = y))+ geom_boxplot()+ geom_jitter()' – jazzurro 2014-09-25 01:17:47

+0

@ jazzurro:您的解決方案有效。發佈它作爲答案。 – rnso 2014-09-25 01:22:47

+0

謝謝你,夥計。完成。 – jazzurro 2014-09-25 01:51:00

1

僅供參考,visreg現在可以輸出gg對象:

visreg(m2, gg=TRUE) 

enter image description here