Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xyplot with confidence interval (box and wisker plot) added in r

I want to add 99% and 95% confidence interval in XYplot.

The following is data:

X <- 1:20
Y <- c(0.5, 1.4, 2.3, 3.4, 4.5,
      3.3, 3.0, 2.1, 1.5, 0,
      0, 3.4, 4.5, 6.7, 5.3, 2.8,
      0.5, 3.4, 3.5,  3.7)
mydata <- data.frame (X, Y)

I want to identify the maximum value of Y and corresponding X value is position of median in box and whisker plot. Whenever the value of Y declines by 1 point (either left or right) is the 99% confidence interval (will be inside the box) and whenever the Y declines to 2 (both left and right), the corresponding positions in x will be represented by the whisker.

Desired plot:

enter image description here

Explanation. enter image description here

corresponding x value to max(Y) = 6.7 corresponding x value to box left = 6.7 - 1, box right = 6.7 - 1 corresponding x value to whisker left = 6.7 - 2, whisker right = 6.7 - 2

like image 960
jon Avatar asked Nov 13 '22 10:11

jon


1 Answers

The following plot should get you started. It uses rectangles rather than a bwplot, and it also doesn't do interpolation.

Create the data:

library(ggplot2)

dat <- data.frame(
    x = 1:20,
    y = c(0.5, 1.4, 2.3, 3.4, 4.5, 3.3, 3.0, 2.1, 1.5, 0, 0, 3.4, 4.5, 6.7, 5.3, 2.8, 0.5, 3.4, 3.5,  3.7)
)

Write a function that returns the 5 desired points:

getRange <- function(x, a=1, b=2){
  maxy <- max(x)
  xMax <- which.max(x)
  x2 <- max(which(x[1:xMax] <= (maxy-a)))
  x1 <- max(which(x[1:x2] <= (maxy-b)))
  x3 <- xMax + min(which(x[-(1:xMax)] < (maxy+a)))
  x4 <- x3 + min(which(x[-(1:x3)] < (maxy+b)))
  data.frame(x1=x1, x2=x2, max=xMax, x3=x3, x4=x4)
}

Get the range values and plot:

rr <- getRange(dat$y, 1, 3)

ggplot(dat, aes(x, y)) + geom_line() + geom_point() +
    geom_rect(data=rr, aes(xmin=x2, xmax=x3, NULL, NULL), 
              ymin=-Inf, ymax=Inf, fill="blue", alpha=0.25) +
    geom_rect(data=rr, aes(xmin=x1, xmax=x4, NULL, NULL), 
              ymin=-Inf, ymax=Inf, fill="blue", alpha=0.25)

enter image description here

like image 116
Andrie Avatar answered Nov 16 '22 18:11

Andrie