2017-01-30 84 views
1

我正在做一個簡單的陰謀與ggplot2,我想添加一個平滑線,錨定(固定)在第一點。我使用了描述here的技巧,但它看起來像我需要通過添加差異y[1] - predict(lm, data.frame(y=5))來重新調整擬合值。我該怎麼做呢?有沒有更好的辦法?ggplot的錨點geom_smooth

library(ggplot2) 
set.seed(3) 

d = data.frame(x=5:14) 
d$y = log(d$x^2) + rnorm(10,0,2) 

ggplot(d, aes(x, y)) + 
    geom_point() + 
    geom_smooth(method='lm', formula = y ~ poly(x,4), se=F) + 
    geom_smooth(method='lm', formula = I(y-y[1]) ~ 0 + poly(x-x[1],4), se=F, color='red') 

Result

+1

擬合模型ggplot之外,則得到一個數據幀和使用的預測和偏移預測geom_line將此添加到繪圖 –

回答

2

試試這個,它應該工作:

m <- lm(I(y-y[1]) ~ 0 + poly(x-x[1],4), data=d) # model without intercept 

ggplot(d, aes(x, y)) + 
    geom_point() + 
    geom_smooth(method='lm', formula = y ~ poly(x,4), se=F) + 
    geom_line(data=data.frame(x=d$x, 
    # the intercept is y[1] - poly(x)[1,]*coeff (it's not computed by lm) 
    # y = prediction by the model + the intercept 
    y = poly(d$x,4)%*%m$coefficients + d$y[1]-as.numeric(poly(d$x,4)[1,]%*%m$coefficients)), 
    aes(x,y), color='red') 

enter image description here

+1

謝謝。爲了使紅線更平滑,我想我應該增加'x'的分辨率。 – sirallen

+0

是的,它應該工作。 –