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

阿多尼斯·塞德诺

在制作与深度和沉降时间相关的移动列线图时,如果曲线低于其上十个(7 到 10 和 18 到 20),我需要拟合曲线(作为抛物线)来移动标签。这非常接近我的需要。

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

在此处输入图像描述

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章