根据是否满足条件对绘图区域进行着色

Bes*_*irl 3 r ggplot2

我正在使用ggplot()和geom_line()为随着时间的推移而发展的价值走廊创建线图。

有时可能会发生上限低于下限(我将其称为“反转”),并且我想突出显示在我的图中发生这种情况的区域,例如使用不同的背景颜色。

搜索 Google 和 StackOverflow 都没有给我带来任何结果。

这是一个人为的例子:

library(tidyverse)
library(RcppRoll)

set.seed(42)
N <- 100
l <- 5
a <- rgamma(n = N, shape = 2)
d <- tibble(x = 1:N, upper = roll_maxr(a, n = l), lower = roll_minr(a + lag(a), n = l)) %>% mutate(inversion = upper < lower)
dl <- pivot_longer(d, cols = c("upper", "lower"), names_to = "Bounds", values_to = "bound_vals")

ggplot(dl, mapping = aes(x = x, y = bound_vals, color = Bounds)) + geom_line(linewidth = 1) + theme_light()
Run Code Online (Sandbox Code Playgroud)

这会产生以下图:

示例图

正如您所看到的,反转发生在一些地方,例如 周围x = 50。我希望该图有一个较暗的(比如灰色)背景,基于inversion小标题中已有的列。我怎样才能做到这一点?

非常感谢你的帮助!

ste*_*fan 5

实现您想要的结果的一种选择是ggh4x::stat_difference像这样使用。请注意,为此我们必须使用宽数据集并相应地通过两个geom_line.

library(ggplot2)
library(ggh4x)

ggplot(d, mapping = aes(x = x)) + 
  stat_difference(aes(ymin = lower, ymax = upper)) +
  geom_line(aes(y = lower, color = "lower"), linewidth = 1) + 
  geom_line(aes(y = upper, color = "upper"), linewidth = 1) + 
  scale_fill_manual(values = c("+" = "transparent", "-" = "darkgrey"),
                    breaks = "-",
                    labels = "Inversion") +
  theme_light() +
  labs(color = "Bounds")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑当然也可以为交叉区域绘制背景矩形。但我不知道有任何开箱即用的选项,即棘手的部分是计算线相交处的 x 值,这需要一些努力和近似。这是一种方法,但可能不是最有效的方法。

library(ggplot2)
library(ggh4x)

ggplot(d, mapping = aes(x = x)) + 
  stat_difference(aes(ymin = lower, ymax = upper)) +
  geom_line(aes(y = lower, color = "lower"), linewidth = 1) + 
  geom_line(aes(y = upper, color = "upper"), linewidth = 1) + 
  scale_fill_manual(values = c("+" = "transparent", "-" = "darkgrey"),
                    breaks = "-",
                    labels = "Inversion") +
  theme_light() +
  labs(color = "Bounds")
Run Code Online (Sandbox Code Playgroud)