2017-02-14 196 views
0

這裏有點新手問題。我想用ggplot2來繪製我的多元迴歸模型,但是我遇到了一個錯誤。在決定詢問社區之前,我在論壇上做了一些研究。錯誤地發佈了original question錯誤的論壇。繪製ggplot2中的多元迴歸線

我知道如何繪製一個簡單線性迴歸:

ggplot(data, aes(x=X, y=Y))+geom_point()+ 
    geom_smooth(method='lm',formula=Y~X) 

但是,當我試圖做多回歸:

Model<-lm(Y~x1*x2*x3*x4*x5, data, na.action=na.omit) 

ggplot(data, aes(x=X, y=Model))+geom_point()+ 
    geom_smooth(method='lm',formula=Y~x1*x2*x3*x4*x5) 

我得到這個錯誤:

Don't know how to automatically pick scale for object of type lm. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (209): x, y

回答

0

您是否嘗試過使用abline()函數?

嘗試使用

abline(Model,lwd=3,col="red") 
+1

請正確格式化你的代碼,無論是把它放在反引號之間或縮進它。你的答案的內容很好,我正在評論這個外觀。 – Dario

0

如果你有兩個獨立的變量,你可以嘗試一下本作多元迴歸,

set.seed(1) 
data <- data.frame(x1=rnorm(100, 5, 2), x2=rnorm(100, 10, 5)) # some random data 
data$y <- 3*data$x1 + 2*data$x2 + rnorm(100, 2, 5) 

lmFit <- lm(y ~ x1 + x2, data = data) 

x1 <- seq(from = min(data$x1), to = max(data$x1), by = 0.1) 
x2 <- seq(from = min(data$x2), to = max(data$x2), by = 0.1) 
y <- outer(X = x1, Y = x2, FUN = function(x1, x2) { 
    predict(lmFit, newdata = data.frame(x1 = x1, x2 = x2)) 
}) 

open3d() 
bg3d("white") 
material3d(col="black") 
persp3d(x1, x2, y, col = "green3", xlab = "x1", ylab = "x2", zlab = "y",theta=50, phi=25, expand=0.75, ticktype="detailed") 
points3d(data$x1, data$x2, data$y, col = "red", size=5) 

enter image description here