R语言 使用自定义函数进行平滑

gijlo24d  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(132)

我最近刚开始学习R,在绘图时使用自定义函数时遇到了一个问题。我想使用rosin-rammler方程,但不知道如何在我的情况下使用它。在Mathkad中,这个问题很容易解决。在这里我不明白。
这是我的数据和代码的一个例子。
| xy|年|第1类|半成品1|
| - ------|- ------|- ------|- ------|
| 无|无|无|1号|
| 十个|三个|无|1号|
| 二十个|三十|无|1号|
| 三十|十八|无|1号|
| 四十|十五|无|1号|
| 五十|十三|无|1号|
| 六十|八个|无|1号|
| 七十|五个|无|1号|
| 八十|三个|无|1号|
| 九十|第二章|无|1号|
| 一百|无|无|1号|
| 一百一十|无|无|1号|

ggplot(allOnw, aes(x = xy, y=yy, col = sem1)) +geom_point()+
  guides(fill = FALSE) +  labs(col="S" )+theme(legend.position="bottom")  +scale_x_continuous(breaks = seq(from = 0, to = 160, by = 10), limits = c(0,160))+
  scale_color_manual(values = c("blue", "cyan", "darkgreen","darkorange","gold","darkorchid")) + 
  facet_wrap(vars(cat1),ncol = 1, strip.position = "right")+labs(x ="MP")+labs(y = "GT ")

我希望使用geom_density时图形看起来像这样。我能做些什么呢?有可能吗?

tpxzln5u

tpxzln5u1#

如果您有一个特定的模型来拟合您的点,则可以在geom_smooth中使用method = nls
就我从literature中了解到的情况而言,您尝试拟合的函数采用以下形式:

rosin_rammler <- function(x, A, B, C) {
  C * ((A / x) * (x / B)^A * exp(-((x / B)^(A - 1))))
}

我们可以直接在geom_smooth中使用它:

ggplot(allOnw, aes(x = xy + 1e-6, y = yy, col = sem1)) +
  geom_point() +
  geom_smooth(formula = y ~ rosin_rammler(x, A, B, C), method = nls,
              method.args = list(algorithm = "port",
                                 start = list(A = 5, B = 20, C = 1000), 
                                 lower = c(1, 1)), se = FALSE, n = 1000) +
  labs(col = "S", x = "MP", y = "GT")+
  theme(legend.position = "bottom")  +
  scale_x_continuous(breaks = 0:16 * 10, limits = c(0, 160)) +
  scale_color_manual(values = c("blue", "cyan", "darkgreen", 
                                      "darkorange", "gold", "darkorchid")) + 
  facet_wrap(vars(cat1), ncol = 1, strip.position = "right")

相关问题