You can also set colors without any additional package as long as you are not using a color scale for grouping data, as this answer relies on `scale_color_identity()`.
``` r
library(ggplot2)
library(ggpmisc)
#> Loading required package: ggpp
#>
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#>
#> annotate
set.seed(4321)
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"))
formula <- y ~ poly(x, 1, raw = TRUE)
ggplot(my.data, aes(x, y)) +
facet_wrap(~ group) +
geom_point() +
geom_smooth(method = "lm", formula = formula) +
stat_poly_eq(formula = formula,
label.x = "left",
mapping = aes(
color = ifelse(after_stat(r.squared) > 0.81,
"red", "black"
)
)) +
scale_color_identity()
```
![](https://i.imgur.com/umMHyBG.png)
<sup>Created on 2022-05-29 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)</sup>
Updated package 'ggpmisc' in version 0.4.0.9000 so that `stat_poly_eq()` now also returns `n` and `n.label`. CRAN version of 'ggpmisc' is 0.4.3 as of 2021-09-03. I add the full reprex here for completeness.
``` r
library(ggpmisc)
#> Loading required package: ggpp
#> Loading required package: ggplot2
#>
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#>
#> annotate
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"),
facet = c("C", "D", "E", "F", "G"),
y2 = y * c(0.5,2),
w = sqrt(x))
formula <- y ~ poly(x, 3, raw = TRUE)
ggplot(my.data, aes(x, y, color = group)) +
geom_point() +
geom_smooth(method = "lm", formula = formula) +
stat_poly_eq(aes(label = paste(after_stat(rr.label),
after_stat(n.label),
sep = "*\", \"*")),
formula = formula,
vstep = 0.2) +
facet_grid(facet ~ .)
```
![](https://i.imgur.com/1u7c7y2.png)
<sup>Created on 2021-09-04 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)</sup>