以 R 为基数缺失值的面积图

Area plot with missing values in base R

我想绘制一个面积图,其多边形的底边为零,数据线在每个数据中断处(即开始、结束和可能的)通过垂直线段连接到底边 NAs/NaN).

这是我画的:

我不得不在系列被 NA 打断的地方强制垂直向下分段,并且我在 0s 中做了这个转换 NA。但这不会产生垂直线段,而是产生到达以下 0 的多边形线。我解决了系列开始和结束的问题,在系列的两侧添加了一个 (y = 0, x = 0) 点。

但如果 NA 在系列赛中,这并不能解决问题。

有什么想法吗?

这是一个示例代码(不同的图像):

pollen <- c(45, 257.4, 24.67, 54.6, 89.4, 297, 471.25, 1256.5, 312.25, 969.2, 787.5, 425, NaN, 76.6, 42.67, 38.5, 20.2, 5.67, 15.8, 13.2, 11, 6.25, 6.67, 2.3, 0.5, 30.8, 3.75, 3, 2, 2.2, 3.25, 4.5, 9.6, 15.8, 200.2, NaN)

weeks.vec <- c(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40)

plot.ts(y = pollen, x = weeks.vec, col = 'red', ylab = 'Pollen',  xlab = 'Weeks', lwd = 3, xy.labels = F, xy.lines = T)
pollen[is.na(pollen)] <- 0

poly.y <- c(0,pollen,0)
poly.x <- c(weeks.vec[1], weeks.vec, weeks.vec[length(weeks.vec)])

polygon(y = poly.y, x = poly.x, density = NA,border = NA, col = rgb(1,0,0, .3))

我会使用 ggplot2:

pollen <- c(45, 257.4, 24.67, 54.6, 89.4, 297, 471.25, 1256.5, 312.25, 969.2, 787.5, 425, NaN, 76.6, 42.67, 38.5, 20.2, 5.67, 15.8, 13.2, 11, 6.25, 6.67, 2.3, 0.5, 30.8, 3.75, 3, 2, 2.2, 3.25, 4.5, 9.6, 15.8, 200.2, NaN)

weeks.vec <- c(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40)


DF <- data.frame(pollen, weeks.vec)

library(ggplot2)
ggplot(DF, aes(x = weeks.vec, y = pollen)) +
  geom_ribbon(aes(ymin = 0, ymax = pollen), 
              colour = NA, fill = "red", alpha = 0.3) +
  geom_line(colour = "red") + 
  geom_point(colour = "red", size = 3) +
  xlab("Week") + ylab("Pollen") +
  theme_bw()

但是如果你必须使用基础地块:

plot.ts(y = pollen, x = weeks.vec, col = 'red', 
        ylab = 'Pollen',  xlab = 'Weeks', lwd = 3, 
        xy.labels = F, xy.lines = T)

g <- cumsum(!is.finite(pollen))
for (i in unique(g)) {
  y <- pollen[g == i]
  x <- weeks.vec[g == i]
  x <- x[is.finite(y)]
  y <- y[is.finite(y)]
  x <- c(x, rev(x))
  y <- c(y, y * 0)
  polygon(y = y, x = x, density = NA,border = NA, col = rgb(1,0,0, .3))
}