这是一个与我之前的问题相关的问题 geom_smooth with facet_grid and different fitting functions .在那个问题中,我试图在 geom_smooth
中为 ggplot2 的小平面网格中的每个小平面使用不同的拟合函数。 Marco Sandri请提供一个答案,我试图适应使用用户定义的公式而不是现有的公式(例如,lm
、loess
)。这是我的代码。
# Load library
library(ggplot2)
# Load data
data(mtcars)
# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
smooth.call <- match.call()
if(as.numeric(unique(data$PANEL)) == 6) {
# Nonlinear regression
method.name <- eval(parse(text="nls"))
# Specify formula
formula <- as.formula("y ~ a * x^b")
# Add initial parameters
smooth.call[["start"]] <- c(a = 10, b = -0.5)
}else{
# Linear regression
method.name <- eval(parse(text="lm"))
}
# Add function name
smooth.call[[1]] <- method.name
# Perform fit
eval.parent(smooth.call)
}
# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth")
print(p)
在这段代码中,我定义了一个函数 custom.smooth
来选择要拟合的模型。在此示例中,所有模型都是线性回归,但面板 6 除外,面板 6 是用户定义的函数 y ~ a*x^b
。运行此代码会出现错误:
Warning message: Computation failed in
stat_smooth()
: singular gradient matrix at initial parameter estimates
然而,当我使用这些初始参数对面板 6 中的数据运行 nls
时,我没有收到此类错误(即,nls(mpg ~ a * disp^b, mtcars %> % filter(gear == 5, am == 1), start = c(a = 10, b = -0.5))
).这让我觉得 nls
没有看到我指定的起始值。我也试过在 geom_smooth
函数中指定这些参数,如下所示:
p <- p + geom_smooth(method = "custom.smooth", method.args = list(start = c(a = 10, b = -0.5)))
但我遇到了同样的问题。有什么想法可以让我的起始值达到 nls
吗?还是有其他原因导致代码无法正常工作?
最佳答案
这是解决方案,极大地受益于 this post .我不知道为什么以前的版本不起作用,但这似乎工作正常。
# Load library
library(ggplot2)
# Load data
data(mtcars)
# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
smooth.call <- match.call()
if(as.numeric(unique(data$PANEL)) == 6) {
# Nonlinear regression
smooth.call[[1]] <- quote(nls)
# Specify formula
smooth.call$formula <- as.formula("y ~ a * x ^ b")
# Add initial parameters
smooth.call$start <- c(a = 300, b = -0.5)
}else{
# Linear regression
smooth.call[[1]] <- quote(lm)
}
# Perform fit
eval.parent(smooth.call)
}
# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth", se = FALSE)
print(p)
关于R:在 geom_smooth 中的自定义函数中使用时,nls 不获取其他参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44930704/