0

So I am trying to add a simple equation to my graph using the text function in R but for some reason its not working.

This is how I generated my randon simulated data:

a <- 5
b <- 7
sigma <- 3
x <- runif(100, min = 0, max = 50)
n <- length(x)

y <- a + b * x + rnorm(n, 0, sigma)

fakeData <- data.frame(x, y)

Then I plugged in the data frame and added a regression line like so.

ggplot(data = fakeData, aes(y, x)) + 
  geom_point() + 
  geom_smooth(method = 'lm', se = FALSE) +
  labs(x = "random uniform distribution from range 0 - 50.", 
       y = "Linear model points based on the Uniform dist", 
       title = "Fake data simulation") 

Which results in a graph like this

enter image description here

Now all I want to do is add the equation of the line to the graph using the text function but for some reason, R just seems to be throwing errors at me. I tried googling the issue but I wasnt able to resolve it. I tried this method also but the lack of documentation is appalling I have no idea what the guy was doing in the function.

enter image description here

Murtaza Mohsin
  • 142
  • 1
  • 12
  • Did you meant `geom_text` ? – akrun Oct 25 '20 at 20:34
  • `text()` is a base R graphics function and cannot be used with `ggplot`. I would encourage you to use the answer at the duplicate you already identified: https://stackoverflow.com/questions/7549694/add-regression-line-equation-and-r2-on-graph. I'm not sure which answer was appalling, but there are a few answers there. – MrFlick Oct 25 '20 at 20:34
  • @akrun See that's what I thought but my textbook specifically mentions using the text function to display the equation. – Murtaza Mohsin Oct 25 '20 at 20:36
  • Well, `text()` would work if you were just using base `plot()` but you are not. There are different methods required if you are using base R graphics vs ggplot graphics and you basically can't combine them. It's unclear what your textbook may have intended. – MrFlick Oct 25 '20 at 20:38
  • @MrFlick I kid you not this textbook is a mess...For some reason, it has like 4.9 stars but it's so disorganized it's called Statistical Regression and other stories if youre curious. – Murtaza Mohsin Oct 25 '20 at 21:25

1 Answers1

1

Try this with annotate() but you previously have to obtain the coefs model using lm():

library(ggplot2)
#Code
a <- 5
b <- 7
sigma <- 3
x <- runif(100, min = 0, max = 50)
n <- length(x)

y <- a + b * x + rnorm(n, 0, sigma)

fakeData <- data.frame(x, y)
#lm
mod <- lm(y~x,data=fakeData)
lab <- paste0(round(coef(mod)[1],3),'+',paste0(round(coef(mod)[2],3),'x'))
#plot
ggplot(data = fakeData, aes(y, x)) + 
  geom_point() + 
  geom_smooth(method = 'lm', se = FALSE) +
  labs(x = "random uniform distribution from range 0 - 50.", 
       y = "Linear model points based on the Uniform dist", 
       title = "Fake data simulation")+
  annotate(geom='text',x=50,y=30,label=lab,fontface='bold')

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84