0

I have a following scatterplot with a smooth spline

a<-rep(1:50,len=500)
b<-sample(0:5000,500)
c<-round(seq(0,600,len=500))
data_frame<-as.data.frame(cbind(a,b,c))
names(data_frame)<-c("ID","toxin_level","days_to_event")

plot(data_frame$days_to_event,data_frame$toxin_level, xlim=c(600,0),xlab="days before the event",ylab="Toxin level",type="p")
abline(v=0,col="red")

x <- data_frame$days_to_event
y <- data_frame$toxin_level

fit.sp = smooth.spline(y ~ x, nknots=20)
lines(fit.sp, col="blue")

This is the resulting plot

enter image description here

I was wondernig if it is possible to somehow add confidence bands to this curve? I deally I would like it to be in a transparent blue, but any color including gray is OK.

Oposum
  • 1,155
  • 3
  • 22
  • 38
  • 1
    possible [duplicate](http://stackoverflow.com/questions/23852505/how-to-get-confidence-interval-for-smooth-spline) – mtoto Jan 12 '16 at 11:50

1 Answers1

1

Updated: using scale_x_reverse to match your graph more precisely...

How about this using ggplot2?

library(ggplot2)

ggplot(data_frame, aes(x = days_to_event, y = toxin_level)) + geom_point() +
  geom_vline(xintercept = 0, color = "red") + scale_x_reverse() + 
  xlab("Days before the event") + ylab("Toxin Level") + 
  geom_smooth(method = lm, se = TRUE)

Which gives this:

Picture

Or to match your question a bit more:

ggplot(data_frame, aes(x = days_to_event, y = toxin_level)) + geom_point(shape = 1) +
  geom_vline(xintercept = 0, color = "red") + scale_x_reverse() + 
  xlab("Days before the event") + ylab("Toxin Level") + 
  geom_smooth(method = lm, se = TRUE, color = "blue", fill = "lightblue") + 
  theme_bw()

Second Picture

David
  • 9,216
  • 4
  • 45
  • 78
  • As @mtoto pointed out, the non-ggplot version has been asked here: http://stackoverflow.com/questions/23852505/how-to-get-confidence-interval-for-smooth-spline – David Jan 15 '16 at 12:34