# Drawing Spline Regression Model with (B-spline)

**URL:** <https://discourse.mc-stan.org/t/drawing-spline-regression-model-with-b-spline/21283>\
**Category:** brms\
**Tags:** rethinking, visualisation, rstan\
**Created:** [March 13, 2021, 5:37pm UTC](https://discourse.mc-stan.org/t/drawing-spline-regression-model-with-b-spline/21283 "2021-03-13T17:37:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jen1009](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/jen1009/32/10922_2.png) [@jen1009](https://discourse.mc-stan.org/u/jen1009)\
**Post date:** [March 13, 2021, 5:37pm UTC](https://discourse.mc-stan.org/t/drawing-spline-regression-model-with-b-spline/21283/1 "2021-03-13T17:37:22Z")

</div>

I’m trying to draw a regression line like [this picture](https://drive.google.com/file/d/15GPx9EhSqIyKPuK4EXZmsuFgKvCXBCMJ/view?usp=sharing) . However, the result of my code looks like [this](https://drive.google.com/file/d/1hhKR7xdZfi2t-G8zJi06JWfEwOtyRVk_/view?usp=sharing).

What am I missing or where am I wrong? Thank you so much!

```
data("cherry_blossoms")
d <- cherry_blossoms

d2 <- d[complete.cases(d),]

num_knots <- 15
knot_list <- quantile( d2$temp, probs = seq(0, 1, length.out = num_knots ) )
B <- bs(d2$temp, knots=knot_list[-c(1, num_knots)],degree=3, intercept=TRUE)

spline_mdl <- quap(
  alist(
    D ~ dnorm( mu, sigma ),
    mu <- a + B %*% w,
    a ~ dnorm( 100, 10 ),
    w ~ dnorm( 0, 10 ),
    sigma ~ dexp(1)
  ), 
  data = list( D = d2$doy , B = B) ,
  start = list( w=rep( 0 , ncol(B)))
)

mu <- link( spline_mdl , data = d2)
mu_mean <- apply ( mu , 2 , mean )
mu_PI <- apply ( mu , 2 , PI , prob = 0.89)
doy_sim <- sim ( spline_mdl , data = d2)
doy_PI <- apply( doy_sim , 2 , PI , prob = 0.89)

plot(d2$temp , d2$doy , col = col.alpha(rangi2, 0.5), xlab = "Temperature", 
     ylab = "Day of Year" )
lines(d2$temp , mu_mean)
shade( mu_PI , d2$temp)                                     
shade( doy_PI , d2$temp) 

mtext("Splines with 15 knots")

```

The question I’m practicing is the following:  
Model the association between blossom date (doy) and March temperature (temp). Note that there are many missing values in both variables. You may consider a linear model, a polynomial, or a spline on temperature. How well does temperature trend predict the blossom trend?

- Operating System: macOS

---

<div class="post-metadata">

**Author:** ![Solomon](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/solomon/32/2495_2.png) [@Solomon](https://discourse.mc-stan.org/u/Solomon)\
**Post date:** [March 14, 2021, 8:20pm UTC](https://discourse.mc-stan.org/t/drawing-spline-regression-model-with-b-spline/21283/2 "2021-03-14T20:20:57Z")

</div>

[Here](https://bookdown.org/content/4857/geocentric-models.html#splines.) are a couple examples from McElreath’s text using a **brms** + **tidyverse** workflow.
