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

はい、うまくいきます。 –