ggplot2:如何在参考线的上方和下方获得不同的色带

问题描述 投票:1回答:1

我有一个数据来制作一个geom_ribbon,然后是一个geom_line。而现在,我想将红丝上方的色带部分制作成不同的颜色。

enter image description here

情节的数据数据:

#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)
r ggplot2
1个回答
2
投票

我们可以通过创建两条丝带来实现这一目标,一条在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)

但请注意,由于数据的水平分辨率有限,因此情节不太正确:

enter image description here

因此,让我们创建一个新的数据框架,在每个月之间的一堆点上线性插入实际数据并再次创建图表:

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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.