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

落爺英雄遲暮 提交于 2019-12-01 08:14:06

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:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!