简体   繁体   中英

Using ggplot Geom_Ribbon in R to fill under a continuous line

I am trying to use geom_ribbon to fill an area under a geom_smooth line in ggplot and there are gaps under the curve where the color is not shaded. My data consists of six discrete values for proportion values on the y axis. Is there a way to use ymax in geom_ribbon differently to have the color meet the curved line better?

在此处输入图片说明

Here is the reproducible code for the data:

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")

Here is the ggplot code:

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))

You can just use the area geom with the stat_smooth layer. For example

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)

在此处输入图片说明

Thou I really think smoothing should be used when you have a lot of data and want to show a general pattern. Using it like this to "smooth" the line to make it look pretty doesn't make it clear that you have modeled the results and shows data in places where you did not observe it.

You can do something like this.

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)

You can also use geom_line instead of geom_smooth .

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

And remove the color from geom_smooth / geom_line if you want. Just add guides(color = FALSE) or fill if you want to remove that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM