使用'ggpmisc'包可以通过组合要使用paste()
或sprintf()
解析的字符字符串来添加方程。在这个回答中,我将使用sprintf()
。我使用它所包含的示例回答问题。我在这个回答中没有展示,但这种方法支持分组和面板。缺点是模型需要拟合两次,一次绘制拟合线,一次添加方程。
为了找到由stat_fit_tidy()
返回的变量名称,我使用了'gginnards'包中的geom_debug()
,尽管名称依赖于模型公式和方法,但它们相当容易预测。除了添加一个图层geom_debug()
外,还会将其data
输入回显到R控制台上。接下来,一旦我们知道要在标签中使用的变量的名称,我们就可以组装要作为R表达式解析的字符串。
使用
sprintf()
组装标签时,需要将
%
字符转义为
%%
,以便原样返回,因此乘号
%*%
变为
%%*%%
。在 R 表达式中嵌入字符字符串是可能的,而且在这种情况下很有用,但我们需要将嵌入的引号转义为
\"
。
library(tidyverse)
library(ggpmisc)
library(gginnards)
args <- list(formula = y ~ k * e ^ x,
start = list(k = 1, e = 2))
ggplot(mtcars, aes(wt, mpg)) +
stat_fit_tidy(method = "nls",
method.args = args,
geom = "debug")
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 )
创建于2022年9月2日,使用 reprex v2.0.2
nlsTxt [1] "italic(y) == c(k = \"49.66\") %.% c(e = \"0.75\")^italic(x)"
- Aliton Oliveira