r - ggplot 指数平滑,调整参数在 exp 内
问题描述
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
有问题的合身:
但是,如果指数内的参数是合适的,那么趋势线的形式就会变得合理:
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
解决方案
这是一种方法,nls
而不是glm
.
您可以nls
使用提供的列表将其他参数传递给method.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()
正如评论中所讨论的,在图表上获得系数的最佳方法是在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)
推荐阅读
- ruby - 所有 Ruby 命令立即关闭
- python - PyOMO:具有二进制域的变量正在优化为浮点值 b/w 0 和 1
- python - 我可以将 python 字典值拆分为单独的数据帧,其数据帧名称等于它包含的值的键名吗?
- android - 缩放视图时手指坐标抖动
- python - Django 管理员更改多对多标签文本
- alfresco - 如何在 Activiti 5.22.0 中重置边界计时器时间周期和/或持续时间?
- r - 使用组均值跨多个组进行单样本 t.test
- apache - DirectorySlash 关闭配置
- java - 可观察的
不返回java值 - angular - 子元素的父元素上的 Mat 菜单触发器