How to put the regression equation on a graph?

7

In another question , and how to put the regression line on a graph. But how to put the regression equation on the graph? For example:

Or

    
asked by anonymous 22.02.2014 / 14:55

1 answer

7

Here's 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

The hjust=0 serves to inform that the indicated ox is the left limit of the text (default is the center, .5) and vjust=1 is to inform that indicated y is the upper limit of the text (same standard of hjust) / p>     

23.02.2014 / 01:47