gpt4 book ai didi

r - ggplot 指数平滑,在 exp 中调整参数

转载 作者:行者123 更新时间:2023-12-04 10:04:40 25 4
gpt4 key购买 nike

ggplot 提供了各种确定趋势线形式的“平滑方法”或“公式”。但是,我不清楚公式的参数是如何指定的,以及如何获得指数公式来拟合我的数据。换句话说,如何告诉 ggplot 它应该适合 exp 中的参数。

df <- data.frame(x = c(65,53,41,32,28,26,23,19))
df$y <- c(4,3,2,8,12,8,20,15)

x y
1 65 4
2 53 3
3 41 2
4 32 8
5 28 12
6 26 8
7 23 20
8 19 15
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "glm", se=FALSE, color="black", formula = y ~ exp(x)) +
geom_point()

p

有问题的搭配:

enter image description here

但是,如果指数内的参数拟合,则趋势线的形式变得合理:
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "glm", se=FALSE, color="black", formula = y ~ exp(-0.09 * x)) +
geom_point()

p

enter image description here

最佳答案

这是方法 nls 的方法而不是 glm .

您可以将附加参数传递给 nlsmethod.args = 中提供了一个列表.这里我们定义了 a 的起始值和 r要拟合的系数。

library(ggplot2)
ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "nls", se = FALSE,
formula = y ~ a * exp(r * x),
method.args = list(start = c(a = 10, r = -0.01)),
color = "black") +
geom_point()

enter image description here

正如评论中所讨论的,获得图上系数的最佳方法是在 ggplot 之外拟合模型。称呼。
model.coeff <- coef(nls( y ~ a * exp(r * x), data = df, start = c(a = 50, r = -0.04)))

ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "nls", se = FALSE,
formula = y ~ a * exp(r * x),
method.args = list(start = c(a = 50, r = -0.04)),
color = "black") +
geom_point() +
geom_text(x = 40, y = 15,
label = as.expression(substitute(italic(y) == a %.% italic(e)^(r %.% x),
list(a = format(unname(model.coeff["a"]),digits = 3),
r = format(unname(model.coeff["r"]),digits = 3)))),
parse = TRUE)

enter image description here

关于r - ggplot 指数平滑,在 exp 中调整参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61648450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com