0

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?

1
  • What do you mean by "R-squared value plotted"? Commented Jul 9, 2018 at 8:54

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.