与geom_smooth的置信边界相关的条件线颜色

时间:2018-06-12 12:53:33

标签: r ggplot2

我有一张带有置信区间的geom_smooth地块。在那个情节中,我添加了一个辅助线。像这样:

library(ggplot2)

ggplot() +
  # smooth with confidence interval
  geom_smooth(data = mtcars, aes(disp, hp)) +

  # secondary line
  geom_line(aes(x = c(90, 110, 120, 180, 220, 240),
                y = c(100, 120, 130, 150, 160, 170)),
            color = "green", size = 2)

enter image description here

但是,我希望第二行的颜色取决于它是否属于geom_smooth的下限和上限:

enter image description here

如何在平滑间隔中实现线条的这种条件颜色?

1 个答案:

答案 0 :(得分:1)

有点难看,但它确实有效:

# base plot. increase number of points to smooth
library(ggplot2)
p <- ggplot(data = mtcars, aes(disp, hp)) +
  geom_smooth(n = 2000)

# grab x-values, lower and upper limits
d <- ggplot_build(p)$data[[1]][ , c("x", "ymin", "ymax")]

# data for the secondary line 
d2 <- data.frame(disp = c(90, 110, 120, 180, 220, 240),
                 hp = c(100, 120, 130, 150, 160, 170))

# interpolate values at the x values from base plot 
l <- approx(d2$disp, d2$hp, xout = d$x)

# create data frame 
d3 <- data.frame(disp = l$x, hp = l$y)

# remove NA values (outside original x)
d <- d[!is.na(d3$hp), ]
d3 <- d3[!is.na(d3$hp), ]

# create indicator: does y-values ("hp") fall in smooth interval?
d3$inside <- NA
d3$inside <- d3$hp < d$ymin | d3$hp > d$ymax

# create group: does line cross smooth limits?
d3$grp <- cumsum(c(TRUE, diff(d3$inside) != 0))

# add line to base plot
p + geom_line(data = d3, aes(color = inside, group = grp), size = 1.5) +
  scale_color_manual(values = c("green", "red"), guide = "none") +
  theme_classic()

enter image description here

可能有用的相关帖子:

Different colours for values above / below a linear trend line

Kohske在这里回答:geom_ribbon and when below or above y=0