2

I have some continuous data:

  • mean_force - 2700 values reflecting a change of my dependent varibale through 2700 ms
  • sd_force - another 2700 values, a standard deviation of the dependent variable through time

I'm plotting mean_force on a graph, like here:

    x=c(1:2700)
    plot(x, mean_force, ty="l", col="blue", ylim=c(-15, 15),
    ylab="force (mN)", 
    xlab='time (ms)',
    lty=1,lwd=3)

The question is how can I plot SD as well, the way it was done on the picture below (shaded area around the mean)? Is there any simple way to do it in R?

CLICK HERE TO SEE THE PIC

Dave2e
  • 22,192
  • 18
  • 42
  • 50
Alex M
  • 129
  • 1
  • 7
  • Possible duplicate of [How to add shaded confidence intervals to line plot with specified values](https://stackoverflow.com/questions/29743503/how-to-add-shaded-confidence-intervals-to-line-plot-with-specified-values) – Rui Barradas Aug 21 '18 at 14:36
  • @RuiBarradas I don't think it's a duplicate, because the OP here is using base R, while the other question asked about ggplot – camille Aug 21 '18 at 15:37
  • @camille You are right, I will retract the close vote. Thanks, SO will have a new answered question. – Rui Barradas Aug 21 '18 at 15:44

1 Answers1

2

If you are looking for a base graphics solution, maybe this will work for your:

#create data
x<-1:100
mean_force<-0.5*x+rnorm(100)
#assume constant standard deviation across the 
sd<-5
#determine error band
psd<-mean_force+sd
nsd<-mean_force-sd

plot(x, mean_force, ty="l", col="blue", 
     ylab="force (mN)", 
     xlab='time (ms)',
     lty=1,lwd=3)
#draw boundary and fill
lines(x, psd)
lines(x, nsd)
polygon(x=c(x, rev(x)), y=c(psd, rev(nsd)), col="lightblue", density = 40, angle=90)
#redraw line on top
lines(x, mean_force, col="blue",lwd=3)

enter image description here

Dave2e
  • 22,192
  • 18
  • 42
  • 50