在 ggplot2 中按标签拟合分组曲线

Fit grouped curves by label in ggplot2

在制作与沉积深度和时间相关的 Remotion 列线图时,如果它们低于上十个(7 ceils 到 10,18 到 20),我需要将曲线(作为抛物线)拟合到 remotion 标签.这非常接近我需要的。

data.frame(
    depth=rep(seq(0.5, 3.5, 0.5), each=8),
    time=rep(seq(0, 280, 40), times=7),
    ss = c(
        820,369,238,164,107,66,41,33,
        820,224,369,279,213,164,115,90,
        820,631,476,361,287,230,180,148,
        820,672,558,426,353,287,238,187,
        820,713,590,492,402,344,262,230,
        820,722,615,533,460,394,320,262,
        820,738,656,574,492,418,360,303)
) %>% 
transmute(
  depth = depth,
  time = time, 
  R = 100*(1- ss/820)
) %>%
  mutate(G=factor(round(R, digits=-1))) %>%
  ggplot(aes(x=time, y=depth, colour=time))+
  geom_label(aes(label=round(R)))+ 
  scale_y_continuous(trans = "reverse")+
  geom_path(aes(group=G))

但它没有得到抛物线曲线。如何在十位条件下平滑它们?

我不确定这是否是您要查找的内容。我将数据和绘图分开,并为每个组应用 stat_smooth。不幸的是,平滑的线条不遵循配色方案。您还将看到针对创建样条线的方法的一些警告。

plt <- ggplot(df1, aes(x=time, y=depth, colour = time)) +
    geom_label(aes(label=round(R))) + 
    scale_y_continuous(trans = "reverse") +
    geom_path(aes(group=G), size = .6, alpha = .5)

lapply(1:length(unique(df1$G)),
       function(i){
         df2 <- df1 %>% filter(G == unique(G)[i])
         plt <<- plt + 
           stat_smooth(data = df2, size = .5,
                       aes(x = time, y = depth), 
                       se = F,  method = lm, color = "darkred",
                       formula = y ~ splines::bs(x, knots = nrow(df2)))
       })

您可以使用附加参数进一步扩展它。我只是不确定你到底在期待什么。

plt <- ggplot(df1, aes(x=time, y=depth, colour = time)) +
    geom_label(aes(label=round(R))) + 
    scale_y_continuous(trans = "reverse") +
    geom_path(aes(group=G), size = .6, alpha = .5)

lapply(1:length(unique(df1$G)),
       function(i){
         df2 <- df1 %>% filter(G == unique(G)[i])
         # u <- df1 %>% {nrow(unique(.[,c(1:2)]))}
         plt <<- plt + 
           stat_smooth(
             data = df2, size = .5,
             aes(x = time, y = depth), 
             se = F,  method = lm, color = "darkred",
             formula = y ~ splines::bs(x, knots = nrow(df2),
                                       degree = ifelse(nrow(df2) <= 4,
                                                       3, nrow(df2) - 2)))
       })