How to draw a polygon around NA values in R? -


i'm trying draw error region around data using base graphics. i've figured out how polygon, starts act badly if there na values in data.

dat <- rnorm(10, mean = 1:10) depth <- 11:20 sd <- rnorm(10, mean = 1.5, sd = 0.5) col <- "blue" alpha <- .2  col <- adjustcolor(col, alpha.f = alpha) par(mfrow = c(1,2)) plot(dat, depth, type = "o", main = "no nas in dat or depth") x <- c(dat - sd, rev(dat + sd)) y <- c(depth, rev(depth)) polygon(x = x, y = y, col = col, border = na)  dat[7] <- na plot(dat, depth, type = "o", main = "nas in dat or depth") x <- c(dat - sd, rev(dat + sd)) y <- c(depth, rev(depth))  polygon(x = x, y = y, col = col, border = na) 

this gives me following image: the desired outcome if there no nas (left panel) , error when there nas (right panel)

it seems na value divides lower polygon 2 polygons. i'd keep 1 polygon.

here's possible solution using rle function:

set.seed(123) # added reproducibility dat <- rnorm(10, mean = 1:10) depth <- 11:20 sd <- rnorm(10, mean = 1.5, sd = 0.5) col <- "blue" alpha <- .2  col <- adjustcolor(col, alpha.f = alpha) par(mfrow = c(1,2)) plot(dat, depth, type = "o", main = "no nas in dat or depth") x <- c(dat - sd, rev(dat + sd)) y <- c(depth, rev(depth)) polygon(x = x, y = y, col = col, border = na)  dat[7] <- na plot(dat, depth, type = "o", main = "nas in dat or depth") x <- c(dat - sd, rev(dat + sd)) y <- c(depth, rev(depth))  ############################################ ## code print error range starts here: ## ############################################ enc <- rle(!is.na(dat)) endidxs <- cumsum(enc$lengths) for(i in 1:length(enc$lengths)){   if(enc$values[i]){     endidx <- endidxs[i]     startidx <- endidx - enc$lengths[i] + 1      subdat <- dat[startidx:endidx]     subsd <- sd[startidx:endidx]     subdepth <- depth[startidx:endidx]      x <- c(subdat - subsd, rev(subdat + subsd))     y <- c(subdepth, rev(subdepth))      polygon(x = x, y = y, col = col, border = na)   } } 

enter image description here

the idea plot 1 polygon each consecutive non-na block.

since rle, given vector, returns lengths , values of consecutive blocks having same value, use identify blocks not na , plot polygon subsetting original dat, depth , sd vectors.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -