如何更改`ggpubr :: stat_regline_equation`文本?

时间:2020-06-06 18:04:31

标签: r ggplot2 ggpubr

是否可以更改ggpubr::stat_regline_equation的标签?我想在可能的情况下将标签更改为ŷ = -51 + 32cyl,并使用换行符和括号中的标准错误。

library(ggplot2)
library(ggpubr)

ggplot(mtcars, aes(cyl, hp)) +
  geom_smooth(method = "lm") +
  stat_regline_equation()
#> `geom_smooth()` using formula 'y ~ x'

reprex package(v0.3.0)于2020-06-06创建

1 个答案:

答案 0 :(得分:0)

library(ggplot2)
library(broom)
library(stringr)
library(dplyr, quietly = T)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

add_parenthesis <- function(vector){
  out <- as.vector(paste0("(", vector, ")"))
  out
}

coef_label <- function(df){
  coef <- 
    broom::tidy(lm(hp ~ cyl, data = df))[,2] %>% 
    mutate(estimate = round(estimate, 2)) %>%
    pull()

  paste0("ŷ = ", str_c(coef, collapse = " + "), "cyl")
}

se_label <- function(df){
  broom::tidy(lm(hp ~ cyl, data = df))[,3] %>% 
    mutate(std.error = round(std.error, 2)) %>%
    pull() %>%
    add_parenthesis() %>% 
    str_c(., collapse = "  ")
}

eqn_label = coef_label(mtcars)
se = se_label(mtcars)

ggplot(mtcars, aes(cyl, hp)) +
  geom_smooth(method = "lm") +
  annotate(x = 5, y = 200, label = eqn_label, geom = "text") +
  annotate(x = 5, y = 190, label = se, geom = "text")
#> `geom_smooth()` using formula 'y ~ x'

Radzen(v0.3.0)于2020-06-06创建