2017-01-30 83 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

是的,它应该工作。 –