Fill region between two loess-smoothed lines in R with ggplot

后端 未结 1 957
甜味超标
甜味超标 2020-11-29 06:41

I\'d like to know how to fill the area between to loess-smoothed lines in ggplot.

The following data frame is used for the pictures:

    x         y          


        
1条回答
  •  温柔的废话
    2020-11-29 07:18

    A possible solution where the loess smoothed data is grabbed from the plot object and used for the geom_ribbon:

    # create plot object with loess regression lines
    g1 <- ggplot(df) + 
      stat_smooth(aes(x = x, y = ymin, colour = "min"), method = "loess", se = FALSE) +
      stat_smooth(aes(x = x, y = ymax, colour = "max"), method = "loess", se = FALSE)
    g1
    
    # build plot object for rendering 
    gg1 <- ggplot_build(g1)
    
    # extract data for the loess lines from the 'data' slot
    df2 <- data.frame(x = gg1$data[[1]]$x,
                      ymin = gg1$data[[1]]$y,
                      ymax = gg1$data[[2]]$y) 
    
    # use the loess data to add the 'ribbon' to plot 
    g1 +
      geom_ribbon(data = df2, aes(x = x, ymin = ymin, ymax = ymax),
                  fill = "grey", alpha = 0.4)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题