在ggplot中设置黄土线置信区间阴影的限制

Jam*_*mes 6 r ggplot2 loess

我在 ggplot 中正确显示黄土线时遇到问题。我有几个变量,其中没有一个可以低于零,例如身高、体重和丰度。我正在尝试用黄土线在 ggplot 中绘制这些数据。使用一些虚构的数据:

library(ggplot2)

df <- as.data.frame(rep(1:7, each = 5))

df[,2] <- c(0,1,5,0,6,0,7,2,9,1,1,18,4,2,34,8,18,24,56,12,12,18,24,63,48,
       40,70,53,75,98,145,176,59,98,165)

names(df) <- c("x", "y")

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits = c(-20,200))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这很好,只是显示平滑线周围置信区间的阴影区域低于零,并且审阅者指出这是不可能的,并要求我更改它。我认为通过将 y 轴的下限设置为零可以轻松完成此操作:

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  geom_smooth() +
  scale_y_continuous(limits = c(0,200))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但这使得黄土线周围的部分阴影区域消失了。有没有一种方法可以使绘图在 y 轴限制为零的情况下工作,以便切断部分阴影区域,或者首先对黄土线设置限制,以便它不会创建阴影低于零的区域?

use*_*1_G 5

 ggplot(df, aes(x=x, y=y)) +
   geom_point() +
   geom_smooth() +
   coord_cartesian(ylim = c(0,200))
Run Code Online (Sandbox Code Playgroud)

  • 是的,这确实解决了OP的问题,并且是一个明显更简单的解决方案。这应该是最重要的答案。 (5认同)

GGa*_*mba 4

我们可以计算 override ymina 的 aes stat_smooth(注意与 的区别geom_smooth):

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  stat_smooth(geom='ribbon', aes(ymin = ifelse(..ymin.. < 0, 0, ..ymin..)), 
              alpha = .3) +
  geom_smooth(se = FALSE) +
  scale_y_continuous(limits = c(-20,200))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.0)于 2018-05-22 创建。