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:
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) } }
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
Post a Comment