2017-02-22 21 views
0

我設法繪製了一條廣義線,但它與我的需求無關。我想繪製每個治療和ID的線,並獲得迴歸值。圖片附在這裏: enter image description here如何擬合每組的迴歸線(每個組包含兩個不同的因子/列)?

我是相對較新的R並找不到正確的答案在線。由於

這是我的數據:

enter image description here

我要繪製的迴歸線治療(0/4/8)*和患者類型的每個組合。

我寫的代碼是:

plot(ion_chlorophyll$NA,ion_chlorophyll$CHL) 
plot(ion_chlorophyll$NA,ion_chlorophyll$CHL, pch = 1,cex = 1, col = "blue", main = "NA relationship", xlab ="Na", ylab ="CHL") 
+0

你應該包括創建的代碼最終數據和圖表以及原始數據的前7到10行,以便人們可以幫助您獲得想要的位置。 – sconfluentus

+0

請幫助我們提供一個可重現的示例 - 即您的數據樣本和您正在運行的代碼,以幫助我們。對於數據示例,將'dput(data_sample)'的輸出粘貼到您的問題中。我們可能只需要大約10行數據,但一定要包含至少兩個治療ID的數據。 – eipi10

+0

感謝您的回答和信息。我將編輯問題 – Yoav

回答

0

,如果你想獲得多個迴歸線嘗試使用xyplot。 使用虹膜數據集進行實驗。

library(lattice) 

xyplot(Sepal.Length ~ Sepal.Width, data = iris, pch = 16, type = c("p", "g", "r"), groups = Species, auto.key = TRUE) 

如果你只是有利於將2D情節三個因素,那麼它應該不會太麻煩,以獲得迴歸線是這樣的:

model1 <- lm(iris$Sepal.Length[iris$Species == "setosa"] ~ iris$Sepal.Width[iris$Species == "setosa"]) 

model2 <- lm(iris$Sepal.Length[iris$Species == "versicolor"] ~ iris$Sepal.Width[iris$Species == "versicolor"]) 

model3 <- lm(iris$Sepal.Length[iris$Species == "virginica"] ~ iris$Sepal.Width[iris$Species == "virginica"]) 

,做的每一個的summary()獲得迴歸線方程的模型。

我認爲你應該這樣做。

enter image description here

+0

有沒有人知道我可以如何在圖表中創造傳奇實體點?我試圖修復這個傳說,但我不知道如何解決它。我可能需要用auto.key做些什麼,正確的,但是什麼? – xyz123

0

你可以用ggplot2做,如果你只是想繪製。您可以使用dplyrtidybroom從模型中獲取預測結果。如果df與列的數據幀 - 處理,patient_type,Leaf_NA,Total_Chl,

剛剛繪製

library(ggplot2) 
p <- df %>% ggplot(aes(Leaf_NA, Total_Chl)) + 
    facet_grid(treatment ~ patient_type) + 
    stat_smooth(method='lm') 
p 

獲取模型預測

library(dplyr) #for group_by(), inner_join(), mutate() 
library(tidyr) #for nest(), unnest() 
library(broom) #for augment() 

model <- df %>% 
    group_by(treatment, patient_type) %>% 
    do(fit = lm(Total_Chl ~ Leaf_NA, data = .)) 

df %>% 
    group_by(treatment, patient_type) %>% 
    nest() %>% 
    inner_join(model, .) %>% 
    mutate(pred = list(augment(fit))) %>% 
    unnest(pred) 
相關問題