ggplot2: geom_smooth select observations connections (equivalence to geom_path())

前端 未结 1 1577
陌清茗
陌清茗 2021-01-06 20:29

I am using ggplot2 to create vertical profiles of the ocean. My raw data set creates \"spikes\" so to make smooth curves. I am hoping to use geom_smooth()

相关标签:
1条回答
  • 2021-01-06 21:02

    The data that you provided is quite minimal, but we can make it work.

    Using some of the tidyverse packages we can fit separate loess functions to each of the variables.

    What we do, essentially, is

    1. Group our data by variable (group_by).
    2. Use do to fit a loess function to each group.
    3. Use augment to create predictions from that loess model, in this case for a 1000 values within the range of the data (for that variable).

    .

    # Load the packages
    library(dplyr)
    library(broom)
    
    lo <- melteddf %>% 
      group_by(variable) %>% 
      do(augment(
        loess(value ~ Depth, data = .), 
        newdata = data.frame(Depth = seq(min(.$Depth), max(.$Depth), l = 1000))
      ))
    

    Now we can use that predicted data in a new geom_path call:

    ggplot(melteddf, aes(y = Depth, x = value)) + 
      facet_wrap(~ variable, nrow = 1, scales = "free_x") + 
      scale_y_reverse() +
      geom_path(aes(col = 'raw')) +
      geom_path(data = lo, aes(x = .fitted, col = 'loess'))
    

    (I map simple character vectors to the color of both lines to create a legend.)

    Result:

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