MYa*_*208 14 r nls ggplot2 lm ggpmisc
R包ggpmisc可用于显示lm模型和poly模型的方程ggplot2(参见此处参考).想知道如何使用nls模型方程结果.以下是我的MWE.ggplot2ggmisc
library(ggpmisc)
args <- list(formula = y ~ k * e ^ x,
start = list(k = 1, e = 2))
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
stat_fit_augment(method = "nls",
method.args = args)
Run Code Online (Sandbox Code Playgroud)
受到您链接的帖子的启发。用于geom_text在提取参数后添加标签。
nlsFit <-
nls(formula = mpg ~ k * e ^ wt,
start = list(k = 1, e = 2),
data = mtcars)
nlsParams <-
nlsFit$m$getAllPars()
nlsEqn <-
substitute(italic(y) == k %.% e ^ italic(x),
list(k = format(nlsParams['k'], digits = 4),
e = format(nlsParams['e'], digits = 2)))
nlsTxt <-
as.character(as.expression(nlsEqn))
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
stat_fit_augment(method = "nls",
method.args = args) +
geom_text(x = 5, y = 30, label = nlsTxt, parse = TRUE)
Run Code Online (Sandbox Code Playgroud)
paste()还可以使用包“ggpmisc”添加方程,用or组装要解析的字符串sprintf()。在这个答案中我将使用sprintf(). 我使用其中包含的示例来回答这个问题。我没有在这个答案中展示这一点,但这种方法支持分组和方面。缺点是模型需要拟合两次,一次绘制拟合线,一次添加方程。
stat_fit_tidy()为了查找我使用包“gginnards”返回的变量的名称geom_debug(),尽管这些名称即使依赖于模型公式和方法也很容易预测。geom_debug()回声不是添加绘图层而是data输入到 R 控制台。接下来,一旦我们知道了希望在标签中使用的变量名称,我们就可以将要解析的字符串组装为 R 表达式。
当用 1 组装标签时,sprintf()需要将要%返回的字符转义为不变%%,因此乘号%*%变为%%*%%。在 R 表达式中嵌入字符串是可能的,并且在这种情况下很有用,但我们需要将嵌入的引号转义为\"。
library(tidyverse)
library(ggpmisc)
#> Loading required package: ggpp
#>
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#>
#> annotate
library(gginnards)
args <- list(formula = y ~ k * e ^ x,
start = list(k = 1, e = 2))
# we find the names of computed values
ggplot(mtcars, aes(wt, mpg)) +
stat_fit_tidy(method = "nls",
method.args = args,
geom = "debug")
Run Code Online (Sandbox Code Playgroud)

#> Input 'data' to 'draw_panel()':
#> npcx npcy k_estimate e_estimate k_se e_se k_stat e_stat
#> 1 NA NA 49.65969 0.7455911 3.788755 0.01985924 13.10713 37.54378
#> k_p.value e_p.value x y fm.class fm.method fm.formula
#> 1 5.963165e-14 8.861929e-27 1.70855 32.725 nls nls y ~ k * e^x
#> fm.formula.chr PANEL group
#> 1 y ~ k * e^x 1 -1
# plot with formula
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
stat_fit_augment(method = "nls",
method.args = args) +
stat_fit_tidy(method = "nls",
method.args = args,
label.x = "right",
label.y = "top",
aes(label = sprintf("\"mpg\"~`=`~%.3g %%*%% %.3g^{\"wt\"}",
after_stat(k_estimate),
after_stat(e_estimate))),
parse = TRUE )
Run Code Online (Sandbox Code Playgroud)

创建于 2022-09-02,使用reprex v2.0.2
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |