How to put the regression equation on a graph?

Asked

Viewed 3,287 times

7

On another question saw how to put the regression line on a graph. But, how to put the regression equation in the graph? For example:

inserir a descrição da imagem aqui

Or

inserir a descrição da imagem aqui

3 answers

7


Follows a possible solution, using geom_text:

set.seed(1)
x <- rnorm(100)
y <- rnorm(100) + 2*x +10
modelo <- lm(y~x)
coeficientes <- modelo$coefficients
texto <- sprintf('y = %.2f + %.2fx, r² = %.2f', coeficientes[1], coeficientes[2], summary(modelo)$r.squared)

require(ggplot2)
dados <- data.frame(x=x, y=y) # O ggplot2 exige que os dados estejam em um data.frame

p <- ggplot(dados, aes(x=x, y=y)) + # Informa os dados a serem utilizadps
    geom_point() +
    geom_text(aes(x=min(x), y=max(y), label=texto), hjust=0, vjust=1)
p

Gráfico obtido The hjust=0 serves to inform that the x indicated is the left limit of the text (default is center, .5) and vjust=1 serves to inform that the y indicated is the upper limit of the text (same as the hjust pattern).

1

It is also possible to automate these output with the function stat_poly_eq package ggpmisc.

library(ggplot2)
library(ggpmisc)

set.seed(1)
x <- rnorm(100)
y <- rnorm(100) + 2*x +10
dados <- data.frame(x = x, y = y)

formula <- y ~ x

ggplot(dados, aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = "lm", se = T, color = "black", formula = formula) +
  ggpmisc::stat_poly_eq(aes(label =  paste(..eq.label.., ..adj.rr.label..,
                            sep = "~~~~")), 
                        formula = formula, parse = TRUE)

inserir a descrição da imagem aqui

ggplot(dados, aes(x = x, y = y)) +
  geom_point() +
  ggpmisc::stat_poly_eq(aes(label = paste(..eq.label.., ..adj.rr.label..,
                            sep = "~~~~")),
                        formula = formula, parse = TRUE)

inserir a descrição da imagem aqui

0

To be registered one more option: the function ggpubr::stat_regline_equation. The syntax is the same as ggpmisc::stat_poly_eq:

library(ggplot2)
library(ggpubr)

ggplot(dados, aes(x, y)) +
  geom_point() +
  geom_smooth(method = "lm") +
  stat_regline_equation(aes(label =  paste(..eq.label.., ..rr.label.., sep = "*plain(\",\")~~")))

If formula is not specified, assume y ~ x.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.