WoeIs
WoeIs

Reputation: 1083

Adding the R-squared for a linear regression plot (ggplot2)?

I've been trying different suggestions such as the ggmisc package, but nothing seems to work in my favor.

I'm using the iris dataframe and just trying to plot random variables:

modellm <- lm(`Sepal.Length` ~ `Sepal.Width` + `Petal.Length` + `Petal.Width`, data = iris)

model <- coef(Modellm)["(Intercept)"] + 
  coef(Modellm)["Sepal.Width"] * iris$`Sepal.Width` + 
  coef(Modellm)["Petal.Length"] * iris$`Petal.Length` + 
  coef(Modellm)["Petal.Width"] * iris$`Petal.Width` + 
  residuals(Modellm)

library(ggplot2)
ggplot(iris, aes(`Sepal.Length`, model))+ 
  geom_point(size=2, alpha=0.2)+
  geom_smooth(method='lm')

How is it possible for me to get the R-squared value plotted in the ggplot?

Upvotes: 0

Views: 2050

Answers (2)

jay.sf
jay.sf

Reputation: 72994

If you really want to plot the R^2, you could do something like this.

library(ggplot2)
p <- ggplot(iris, aes(`Sepal.Length`, model))+ 
  geom_point(size=2, alpha=0.2)+
  geom_smooth(method='lm')

r2 <- summary(Modellm)$r.squared

p + scale_y_continuous(
  sec.axis=sec_axis(~ . * 4 / 30 , name = expression(paste(R^{2})))) +
  geom_rect(xmin=7.9, xmax=8, ymin=0, ymax=1*30/4, 
            fill="white", color="#78B17E") +
  geom_rect(xmin=7.9, xmax=8, ymin=0, ymax=r2*30/4, fill="#78B17E") + 
  annotate("text", x = 7.95, y = 7.62, size=3, color="#78B17E",
           label = paste0(round(r2, 2)))

Yields

enter image description here

Upvotes: 1

Shinobi_Atobe
Shinobi_Atobe

Reputation: 1973

If you want to display the r squared value just add this to the end of your plot:

 + annotate("text", x = 1, y = 1, label = paste0("R Squared = ", summary(modellm)$r.squared))

adjust the placement with the x and y coordinates

Upvotes: 2

Related Questions