1
x <- 1:100
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x = x, y = y,
                      group = c("A", "B"),
                      y2 = y * c(0.5,2),
                      w = sqrt(x))

formula <- y ~ poly(x, 3, raw = TRUE)

ggplot(my.data, aes(x, y)) +
  geom_point() +
  geom_smooth(method = "lm", formula = formula) +
  stat_poly_eq(formula = formula, parse = TRUE)

像这样:

在此处输入图像描述

4

2 回答 2

1
ggplot(my.data, aes(x, y)) +
  geom_point() +
  geom_smooth(method = "lm", formula = formula) + 
  ggpmisc::stat_poly_eq(aes(label = paste(stat(rr.label), paste("N ~`=`~", nrow(my.data)), sep = "*\", \"*")), formula = formula, parse=T)

您可以使用aes. 由于字符串已解析,因此您必须使用 . 转义等号~`=`~

编辑:带刻面

您可以创建一个额外的未使用的组行计数映射,用作粘贴语句中的变量,而不是nrow(my.data).

ggplot(my.data %>% group_by(group) %>% mutate(n = n()), aes(x, y, n = n)) +
  geom_point() +
  geom_smooth(method = "lm", formula = formula) +
  facet_grid(vars(group)) + 
  ggpmisc::stat_poly_eq(aes(label = paste(stat(rr.label), paste("N ~`=`~", n), sep = "*\", \"*")), 
                        formula = formula, parse=T)
于 2021-05-28T20:01:40.207 回答
0

我发现了这种方法:

library(gginnards)
ggplot(my.data, aes(x, y)) +
+     geom_point() +
+     geom_smooth(method = "lm", formula = formula) +
+     stat_poly_eq(formula = formula, geom = "debug",
+                  summary.fun = colnames)

这给了我以下清单:

Input 'data' to 'draw_panel()':
 [1] "npcx"          "npcy"          "label"         "eq.label"     
 [5] "rr.label"      "adj.rr.label"  "AIC.label"     "BIC.label"    
 [9] "f.value.label" "p.value.label" "n.label"       "grp.label"    
[13] "r.squared"     "adj.r.squared" "p.value"       "n"            
[17] "x"             "y"             "PANEL"         "group" 

结合本站信息:https ://www.rdocumentation.org/packages/ggpmisc/versions/0.4.3/topics/stat_poly_eq

你应该能够解决你的大部分问题。

于 2021-12-15T21:04:52.537 回答