2009-09-25 5 views
11

나는 일부 데이터, 나는 선형 및 이차 LM 모형ggplot2의 산점도상의 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) 

나는 모두를 만든있는

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 

이 그런 다음 ggplot2를 사용하여 데이터 값을 플롯 할 수 있습니다.

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

두 개의 객체를 나타내는 선을 오버레이하는 방법은 없습니다. ?

답변

29

가장 쉬운 방법은 geom_smooth()를 사용하여 ggplot2를 모델에 맞게 설정하는 것입니다.

Illustration using geom_smooth

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() 
아니면 예측 값을 갖는 새 데이터 집합을 만들 수 있습니다.

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

Thierry, 결과 이미지를 게시 하시겠습니까? 감사! –

9

이전에 나는 관련 질문을했고, 해들리는 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