2016-07-14 115 views
1

我有一個簡單的數據有兩個連續變量(囊泡和細胞),並用兩個級別(HC和RA)的單個分組變量設置,這裏模擬:如何繪製組內的非線性迴歸線和ggplot2中的總數據?

###Simulate Vesicle variable### 
Vesicle.hc <- sort(runif(23, 0.98, 5)) #HC group 
Vesicle1.ra <- sort(runif(5, 0.98, 3)) #RA group 
Vesicle <- c(Vesicle.hc, Vesicle1.ra) #Combined 

###Simulate Cells variable### 
z <- seq(23) 
Cells.hc <- (rnorm(23, 50 + 30 * z^(0.2), 8))*runif(1, 50000, 400000) #HC group 
Cells.ra <- c(8.36e6, 6.35e6, 1.287e7, 1.896e7, 1.976e7)    #RA group 
Cells <- c(Cells.hc, Cells.ra)           #Combined 

###Define groups and create dataframe### 
Group <- rep("HC",23)        #HC group 
Group1 <- rep("RA",5)        #RA Group 
Group <- c(Group, Group1)       #Combined 
df <- data.frame(Cells, Vesicle, Group)    #Data frame 

我已經繪製的數據的散點圖使用GGPLOT2與非線性迴歸線(示here),裝配到各組個別地使用:

###Plot data### 
library(ggplot2) 
ggplot(df, aes(x = Cells, y = Vesicle, colour=Group)) + 
    xlab("Stimulated neutrophils") + 
    ylab("MV/cell") + 
    stat_smooth(method = 'nls', formula = 'y~a*exp(b*x)',      #Fit nls model 
       method.args = list(start=c(a=0.1646, b=9.5e-8)), se=FALSE) + #Starting values 
    geom_point(size=4, pch=21,color = "black", stroke=1.5, aes(fill=Group)) #Change point style 

我的問題是,除了繪製每組的非線性迴歸函數,哪能還情節一個迴歸線適合於所有全部數據即對數據建模忽略分組變量的貢獻?

+1

你在創作Cells.hc'的'得到了一個意外的符號存在。另外,我沒有看到'z'的創建位置。 –

+0

我想,用'aes(group = NULL)'添加另一個'stat_smooth'。 – Axeman

+0

哦,我真誠的道歉,當我做出工作示例時,我的環境中已經存在這些變數 - 我有多麼渺茫。現在編輯的代碼應該可以工作。我嘗試了@Axeman的建議,但是雖然沒有錯誤,但情節也沒有改變。 – Hefin

回答

0
ggplot(df, aes(x = Cells, y = Vesicle, colour=Group)) + 
    xlab("Stimulated neutrophils") + 
    ylab("MV/cell") + 
    stat_smooth(method = 'nls', formula = 'y~a*exp(b*x)', 
       method.args = list(start=c(a=0.1646, b=9.5e-8)), se=FALSE) + 
    stat_smooth(color = 1, method = 'nls', formula = 'y~a*exp(b*x)', 
       method.args = list(start=c(a=0.1646, b=9.5e-8)), se=FALSE) + 
    geom_point(size=4, pch=21,color = "black", stroke=1.5, aes(fill=Group)) 

enter image description here

+0

美麗的謝謝你。所以只需添加「color = 1」即可防止stat_smooth繼承組分類。 – Hefin

+0

是的就是這樣。還有一個'inherit.aes'參數,但這意味着你再次定義'x'和'y',所以通常更容易使分組無效。 – Axeman