0

I have the following data and code in R:

x <- runif(1000, -9.99, 9.99)
mx <- mean(x)
stdevs_3 <- mx + c(-3, +3) * sd(x/5) # Statndard Deviation 3-sigma

And I plotted as line (alongwith 3 standard deviation and mean lines) in R:

plot(x, t="l", main="Plot of Data", ylab="X", xlab="")
abline(h=mx, col="red", lwd=2)
abline(h=stdevs_3, lwd=2, col="blue")

Line Plot with mean and SD lines

What I want to do:

Anywhere on the plot, whenever line is crossing 3 sigma thresholds (blue lines), above or below it, line should be in different color than black.

I tried this, but did not work:

plot(x, type="l", col= ifelse(x < stdevs_3[[1]],"red", "black"))
abline(h=mx, col="red", lwd=2)
abline(h=stdevs_3, lwd=2, col="blue")

Is there any other way?

Manoj Kumar
  • 5,273
  • 1
  • 26
  • 33
  • This appears statistically incoherent. Where does this expression come from? `sd(x/5)` – IRTFM Mar 02 '16 at 06:25
  • I deliverately did it, i know staistically it is not good, but to show lines on the plot on the data which is randomly generated. I have data which is confidential and in that i used sd(x) and not like the one shown above. sorry for the confusion. – Manoj Kumar Mar 03 '16 at 08:43

1 Answers1

0

This is what is requested, but it appears meaningless to me because of the arbitrary division of x by 5:

png( )
plot(NA, xlim=c(0,length(x)), ylim=range(x),  main="Plot of Data", ylab="X", xlab="", )
 stdevs_3 <- mx + c(-3, +3) * sd(x/5) 
 abline(h=mx, col="red", lwd=2)
 abline(h=stdevs_3, lwd=2, col="blue")
 segments( 0:999, head(x,-1), 1:1000, tail(x,-1) , col=c("black", "red")[ 
                                       1+(abs(tail(x,-1)) > mx+3*sd(x/5))] )
 dev.off()

enter image description here

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Actually, x was divided by 3 just to bring 3-deviation lines into this picture. I have other data which is confidential and can not be shown on any public websites. sorry for this confusion. but, hey !, nice try. Although it is clear that line has red color even within 3 sigma boundaries. All I needed, any red colored line only when it is outside the 3 sigma lines (top or bottom ones), i.e. outside of +3 and outside of -3 points on Y-axis. – Manoj Kumar Mar 03 '16 at 08:19
  • I could not tell what your expectation was regarding _how_ to color the "lines". At the moment it is coloring segments that cross those boundaries by having their endpoints outside, but the color of the segments may extends into the middle band. Since I've gotten no statement that this is either desired or not, and no upvote or checkmark, I remain uncertain whether the question is answered. – IRTFM Mar 03 '16 at 16:22
  • 1
    I got a better idea.. In dataframe I will calculate the outliers (Yes or No) when a data point is compared with 3-sigma level (both, above and below) and set the color parameter based upon whether or not outlier. – Manoj Kumar Apr 09 '16 at 08:18