How i can get regression line equation and R^2

Hello, I am trying to put regression line equation and R2 on my plot, please let me know if someone know how i can get that.

Here is my code:

library(ggplot2)
df <- read.csv("F:/Chapter6_Files_Figures/scatterplot.csv", stringsAsFactors = F)
colnames(df)[1] = "sample_name"
colnames(df)[2] = "Flavor"
colnames(df)[3] = "JAR"
ggplot(df, aes(x = JAR, y = Flavor)) +
  geom_point(color = "#669999") +
  geom_smooth(method=lm, linetype = "dashed", color="black") +
  coord_cartesian(ylim=c(1, 9)) + 
  scale_y_continuous(breaks=seq(1, 10, 1))
#> `geom_smooth()` using formula 'y ~ x'

Created on 2020-07-07 by the reprex package (v0.3.0)

The ggmsic package makes this fairly simple.

Df <- data.frame(JAR = seq(20, 60, 5),
                 Flavor = c(3, 4.5, 4.9, 6, 7.2, 7.8, 8.3, 8.6, 8.9))
library(ggplot2)
library(ggpmisc)
ggplot(Df, aes(x = JAR, y = Flavor)) +
  geom_point(color = "#669999") +
  geom_smooth(method=lm, linetype = "dashed", color="black") +
  coord_cartesian(ylim=c(1, 10)) + 
  scale_y_continuous(breaks=seq(1, 10, 1)) +
  stat_poly_eq(formula = y ~ x, 
               aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), 
               parse = TRUE)
#> `geom_smooth()` using formula 'y ~ x'

Created on 2020-07-06 by the reprex package (v0.3.0)

2 Likes

why I can not install "ggpmisc" in Rstudio, even can not find from Repository

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

I do not use this package very much so there may be a better way to do this.

ggplot(Df, aes(x = JAR, y = Flavor)) +
  geom_point(color = "#669999") +
  geom_smooth(method=lm, linetype = "dashed", color="black") +
  coord_cartesian(ylim=c(1, 10)) + 
  scale_y_continuous(breaks=seq(1, 10, 1)) +
  stat_poly_eq(formula = y ~ x, 
               aes(label = paste(..eq.label..)), 
               parse = TRUE, label.y = 0.9) +
  stat_poly_eq(formula = y ~ x, 
               aes(label = paste(..rr.label..)), 
               parse = TRUE, label.y = 0.85)
1 Like

Thanks @FJCC for the help. Do you know if i can move R^2 just below of y = 0.644+0.148x?

The CRAN page is here. What happens when you try to install the package? What version of R do you have?

thanks, I got it! because my R version is 3.5.3, but this package need version more than 3.6.0