在R中使用ggplot Geom_Ribbon在连续线下填充

时间:2018-09-27 16:17:21

标签: r ggplot2

我正在尝试使用geom_ribbon来填充ggplot中geom_smooth线下的区域,并且曲线下方存在未着色阴影的间隙。我的数据由y轴上比例值的六个离散值组成。有没有办法在geom_ribbon中不同地使用ymax以使颜色更好地符合曲线?

enter image description here

这是数据的可复制代码:

q1 <- structure(list(Session = 1:6, Counts = c(244L, 358L, 322L, 210L, 
156L, 100L), Density_1000 = c(NA, NA, NA, NA, NA, NA),             Proportion_Activity = c(0.175539568, 
0.257553957, 0.231654676, 0.151079137, 0.112230216, 0.071942446
), Lifestage = structure(c(3L, 3L, 3L, 3L, 3L, 3L), .Label =    c("Adult", 
"Nymph", "Larvae"), class = "factor")), .Names = c("Session", 
"Counts", "Density_1000", "Proportion_Activity", "Lifestage"),    row.names = 13:18, class = "data.frame")

这是ggplot代码:

ggplot(q1,aes(x=Session, y=Proportion_Activity, col =    Lifestage,fill=Lifestage)) 
+ geom_smooth(method = 'loess') 
+ geom_ribbon(data = q1,aes(x = Session, ymin=0,    ymax=Proportion_Activity, alpha=0.5))

2 个答案:

答案 0 :(得分:2)

您可以仅将area几何与stat_smooth图层一起使用。例如

ggplot(q1,aes(x=Session, y=Proportion_Activity, col =    Lifestage,fill=Lifestage))  + 
  geom_smooth(method = 'loess') +
  stat_smooth(se=FALSE, geom="area", method = 'loess', alpha=.5)

enter image description here

我真的认为,当您有大量数据并想要显示一般模式时,应该使用平滑处理。像这样使用它来“平滑”线条以使其看起来很漂亮,这并不能明确表明您已对结果建模,并在未观察到的地方显示了数据。

答案 1 :(得分:0)

您可以执行以下操作。

p1 <- ggplot(q1,aes(x=Session, y=Proportion_Activity)) +
  geom_smooth(method = 'loess', aes(color = Lifestage))

g1 <- ggplot_build(p1)

p2 <- data.frame(Session = g1$data[[1]]$x,
                 Proportion_Activity = g1$data[[1]]$y,
                 Lifestage = structure(g1$data[[1]]$group, .Label = c("Larvae", "Nymph", "Adult"), class = "factor"))


p1 + geom_ribbon(data = p2, aes(x = Session, ymin = 0, ymax = Proportion_Activity, fill = Lifestage), alpha = 0.5)

您也可以使用geom_line代替geom_smooth

geom_line(stat = "smooth", method = 'loess', alpha = 0.5, aes(color = Lifestage))

并根据需要从geom_smooth / geom_line中删除颜色。如果要删除,只需添加guides(color = FALSE)fill