2009-09-25 71 views
11

我有一些數據,如何覆蓋一個LM對象行上GGPLOT2散點圖

calvarbyruno.1<-structure(list(Nominal = c(1, 3, 6, 10, 30, 50, 150, 250), Run = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor"), 
    PAR = c(1.25000000000000e-05, 0.000960333333333333, 0.00205833333333334, 
    0.00423333333333333, 0.0322333333333334, 0.614433333333334, 
    1.24333333333333, 1.86333333333333), PredLin = c(-0.0119152187070942, 
    0.00375925114245899, 0.0272709559167888, 0.0586198956158952, 
    0.215364594111427, 0.372109292606959, 1.15583278508462, 1.93955627756228 
    ), PredQuad = c(-0.0615895732702735, -0.0501563307416599, 
    -0.0330831368244257, -0.0104619953693943, 0.100190275883806, 
    0.20675348710041, 0.6782336426345, 1.04748729725370)), .Names = c("Nominal", 
"Run", "PAR", "PredLin", "PredQuad"), row.names = c(NA, 8L), class = "data.frame") 
calweight <- -2 
爲此,我已經創建了兩個線性和二次LM模型

callin.1<-lm(PAR~Nominal,data=calvarbyruno.1,weight=Nominal^calweight) 
calquad.1<-lm(PAR~Nominal+I(Nominal^2),data=calvarbyruno.1,weight=Nominal^calweight) 

然後可以使用GGPLOT2

qplot(PAR,Nominal,data=calvarbyruno.1) 

繪製我的數據值,但不能工作,如何覆蓋一行表示兩個LM對象...任何想法?

回答

29

最簡單的選擇是使用geom_smooth()讓ggplot2適合你的模型。

ggplot(calvarbyruno.1, aes(y = PAR, x = Nominal, weight=Nominal^calweight)) + 
    geom_smooth(method = "lm") + 
    geom_smooth(method = "lm", formula = y ~ poly(x, 2), colour = "red") + 
    geom_point() + 
    coord_flip() 

Illustration using geom_smooth

或者你可以創建與預測值的新的數據集。

newdata <- data.frame(Nominal = pretty(calvarbyruno.1$Nominal, 100)) 
newdata$Linear <- predict(callin.1, newdata = newdata) 
newdata$Quadratic <- predict(calquad.1, newdata = newdata) 
require(reshape2) 
newdata <- melt(newdata, id.vars = "Nominal", variable.name = "Model") 
ggplot(calvarbyruno.1, aes(x = PAR, y = Nominal, weight=Nominal^calweight)) + 
    geom_line(data = newdata, aes(x = value, colour = Model)) + 
    geom_point() 
+0

蒂埃裏,你介意張貼結果的圖像?謝謝! – 2009-09-25 14:29:04

9

早些時候我問了一個相關的問題,Hadley有this good answer。使用該帖子中的預測功能,您可以向數據添加兩列。其中每個模型:

calvarbyruno.1$calQuad <- predict(calquad.1) 
calvarbyruno.1$callin <- predict(callin.1) 

然後,它的繪製點和增加每個模式作爲一個線的問題:

ggplot() + 
geom_point(data=calvarbyruno.1, aes(PAR, Nominal), colour="green") + 
geom_line(data=calvarbyruno.1, aes(calQuad, Nominal), colour="red") + 
geom_line(data=calvarbyruno.1, aes(callin, Nominal), colour="blue") + 
opts(aspect.ratio = 1) 

這帶來的結果在這個漂亮的圖片(是的顏色可以使用一些工作):

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/09/ggplot2.png