Home > Software design >  R ggplot2 Add text to label geom_text
R ggplot2 Add text to label geom_text

Time:07-13

Based on the function below, how can I add Formula = label = get_formula(model) and R^2(superscript) = label = r_squared?

Because when I do:

....
label = c("Formula = ", get_formula(model))

I get an error:

Error in check_aesthetics(): ! Aesthetics must be either length 1 or the same as the data (42): label

Code:

library(tidyverse)

df = data.frame(x = c(1:100))
df$y = 2   3 * df$x   rnorm(100, sd = 40)
p = ggplot(data = df, aes(x = x, y = y))  
            geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x)  
            geom_point()

get_formula = function(model) {
  
  broom::tidy(model)[, 1:2] %>%
    mutate(sign = ifelse(sign(estimate) == 1, '   ', ' - ')) %>% #coeff signs
    mutate_if(is.numeric, ~ abs(round(., 2))) %>% #for improving formatting
    mutate(a = ifelse(term == '(Intercept)', paste0('y ~ ', estimate), paste0(sign, estimate, ' * ', term))) %>%
    summarise(formula = paste(a, collapse = '')) %>%
    as.character
  
}

lm(y ~ x, data = df) = model
get_formula(model)

scales::percent(summary(model)$r.squared, accuracy = 0.01) = r_squared

# Add the text to the plot:
p   
  geom_text(x = 20, y = 300,
            label = get_formula(model),
            color = 'red')  
  geom_text(x = 20, y = 285,
            label = r_squared,
            color = 'blue')

CodePudding user response:

You need to use paste instead of c to concatenate into a string for the label. For getting the superscript you'll need a bit of unicode (as far as I am aware!):

p   
  geom_text(x = 20, y = 300,
            label = paste0("Formula = ", get_formula(model)),
            color = 'red')  
  geom_text(x = 20, y = 285,
            label = paste0("R\U00B2 = ", r_squared),
            color = 'blue')

enter image description here

  • Related