GGPLOT2:如何获得上述和参考线以下不同颜色丝带(ggplot2: How to get dif

2019-09-28 12:05发布

我有一个数据做出geom_ribbon然后geom_line了它。 而现在,我想提出的红线之上的色带,色不同的部分。

对于绘图数据数据:

#simulate data
dat <- data.frame(1:12)
colnames(dat) <- c("code")
dat$code <- month.abb
dat$code <- factor(dat$code, levels = dat$code)
dat$Th <- c(42, 44, 53, 64, 75, 83, 87, 84, 78, 67, 55, 45)
dat$Tl <- c(27, 28, 35, 44, 54, 63, 68, 66, 59, 48, 38, 29)
dat$prec <- c(3.03, 2.48, 3.23, 3.15, 4.13, 3.23, 4.13, 4.88, 3.82, 3.07, 2.83, 2.8)
dat$prec <- dat$prec*16
dat

#plot
ggplot(data = dat, aes(x = code, ymin = Tl, ymax = Th)) +
  geom_ribbon(group = 1) +
  geom_line(data = dat, aes(x = code, y = prec, group = 2), colour = "red", size = 3) +
  expand_limits(y = 0)

Answer 1:

我们可以通过创建两个带,一个之间做Tlprec之间一个precTh 。 在每一种情况下,我们还需要解决,其中的情况下prec低于或高于分别既ThTl

ggplot(dat, aes(x = code)) +
  geom_ribbon(aes(ymin=pmin(pmax(prec,Tl),Th), ymax=Th, group=1), fill="blue") +
  geom_ribbon(aes(ymin=Tl, ymax=pmax(pmin(prec,Th),Tl), group=2), fill="green") +
  geom_line(aes(y = prec, group = 2), colour = "red", size = 3) +
  expand_limits(y = 0)

但要注意,该地块是因为数据的有限水平分辨率的不完全正确:

因此,让我们创建在一堆每个月之间的点是线性插值的实际数据的新的数据帧,并重新创建情节:

dat.new = cbind.data.frame(
  code=seq(1,12,length=200), 
  sapply(dat[,c("prec","Th","Tl")], function(T) approxfun(dat$code, T)(seq(1,12,length=200)))
  )

ggplot(dat.new, aes(x = code)) +
  geom_ribbon(aes(ymin=pmin(pmax(prec,Tl),Th), ymax=Th, group=1), fill="blue") +
  geom_ribbon(aes(ymin=Tl, ymax=pmax(pmin(prec,Th),Tl), group=2), fill="green") +
  geom_line(aes(y = prec, group = 2), colour = "red", size = 3) +
  expand_limits(y = 0) +
  scale_x_continuous(breaks=1:12, labels=month.abb)



文章来源: ggplot2: How to get different color ribbons above and below a reference line
标签: r ggplot2