2013-01-03 110 views
4

我需要使用ggplot創建多變量回歸線。使用ggplot2進行多變量回歸

我的數據:

dput(head(x2,15)) 
structure(list(Date = structure(c(15608, 15609, 15610, 15611, 
15612, 15613, 15614, 15615, 15616, 15617, 15618, 15619, 15620, 
15621, 15622), class = "Date"), Cpu = c(77.0763, 51.8909, 59.3229, 
89.5822, 87.7448, 80.4413, 57.5009, 99.8185, 99.9969, 91.5528, 
50.0793, 56.4049, 57.808, 51.0453, 56.0505), Memory = c(369.667979452055, 
341.572253381722, 345.013066490241, 334.520135424091, 374.107056613899, 
1592.38342810723, 470.204599904169, 393.802909594735, 540.817571059432, 
425.49563812601, 438.326775174387, 614.417456359102, 1255.63550519358, 
466.993243243243, 358.445879354291), Response = c(52.25, 48.36, 
49.23, 50.99, 48.63, 46.11, 43.03, 45.35, 50.03, 46.18, 47.39, 
43.28, 55.36, 50.59, 50.44)), .Names = c("Date", "Cpu", "Memory", 
"Response"), row.names = c(1L, 4L, 6L, 7L, 9L, 10L, 13L, 16L, 
19L, 25L, 29L, 32L, 35L, 39L, 42L), class = "data.frame") 

我可以ResponseCpu之間做到這一點:

ggplot(x2, aes(Response)) + 
    geom_point(aes(y = Memory), size = 2, colour = "blue") + 
    geom_point(aes(y = Cpu), size = 2, colour = "orange") + 
    geom_smooth(method = "lm", formula = "Response ~ CPU+Memory", 
       size = 1.5, colour = "red", se = T) 

我收到此錯誤:

Error: stat_smooth requires the following missing aesthetics: y 

任何想法?

+0

爲什麼你把你的因變量(響應)放在X軸上?人們會預期它在Y軸上。我相信3D圖會更適合您的數據。 – Roland

回答

6

首先,stat_smooth取公式;我不認爲geom_smooth需要一個。其次,我不認爲你可以在stat_smooth中輸入多於一個predictor的公式。糾正我,如果我錯了。備用解決方案是自己擬合模型和計算預測值,並且還計算並自己繪製SE以這種方式:(從http://docs.ggplot2.org/0.9.3/geom_smooth.html拍攝)

model <- lm(data = df, Response ~ Memory + Cpu) 
df$model <- stats::predict(model, newdata=df) 
err <- stats::predict(model, newdata=df, se = TRUE) 
df$ucl <- err$fit + 1.96 * err$se.fit 
df$lcl <- err$fit - 1.96 * err$se.fit 

g <- ggplot(df) 
g <- g + geom_point(aes(x=Response, y = model), size = 2, colour = "blue") 
g <- g + geom_smooth(data=df, aes(x=Response, y=model, ymin=lcl, ymax=ucl), size = 1.5, 
      colour = "red", se = TRUE, stat = "smooth") 

這給瞭如下圖所示的結果(不知道它是什麼你期望): enter image description here

+4

+1。您可以使用'predict(...,interval =「confidence」)'而不是手工進行+/-'se.fit'計算。 –

+0

@阿倫,謝謝你太棒了。剛剛有一個快速的問題,這似乎是黃土模型。你如何使它成爲線性的? – user1471980

+0

這是計算黃土模型:model〜Response。 OP顯然希望繪製CPU在CPU CPU +內存中的邊際效應。 – Solomon