首页 > 解决方案 > 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

在此处输入图像描述

标签: rggplot2

解决方案


这是一种方法,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)

在此处输入图像描述


推荐阅读