How to fix slope calculation in stat_poly_eq?

115 views Asked by At

I used stat_poly_eq to display the calculated linear equation on the graph, but the displayed results were very different from the actual ones. The actual slope cannot be greater than 0.5. Can anyone help me correct this error? ​

Here is my data:

df<-structure(list(Variety = c("Sultana - MG 000", "ES Pallador - MG I", 
"Isidor - MG I", "Santana - MG I/II", "Blancas - MG II", "Ecudor - MG II"
), FTSWt2017 = c(0.54, 0.47, 0.41, 0.18, 0.25, 0.18), FTSWt2021 = c(0.32, 
0.27, 0.35, 0.29, 0.22, 0.32)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L))

Here is my code:

library(ggplot2)
library(ggpmisc)
library(ggrepel)
library(stringr)
library(stats)
ggplot(df, aes(x = FTSWt2017, y = FTSWt2021)) +
  geom_point(aes(color = Variety)) +
  geom_smooth(method = "lm", formula = 'y ~ x', se=FALSE,color="black") +
  geom_abline(intercept = 0, slope = 1, color="gray", 
              linetype="dashed", size=0.5)+
  (
    aes(label = paste(
      gsub(
        '\\.',
        "*paste('.')*",
        str_replace_all(after_stat(eq.label), "\\.([0-9])[0-9]", "\\.\\1")
      ),
      gsub('\\.', ".", after_stat(rr.label)),
      sep = "*plain(\";\")~~"
    )))

Here is the output figure:

enter image description here

1

There are 1 answers

0
stefan On BEST ANSWER

As you want to round the the displayed coefficients to 2 digits I think the easiest approach would be to set output.type="numeric" which will give you access to a tibble containing the coefficients which makes it much easier to achieve your desired result instead of manipulating the plotmath string:

library(ggplot2)
library(ggpmisc)

ggplot(df, aes(x = FTSWt2017, y = FTSWt2021)) +
  geom_point(aes(color = Variety)) +
  geom_smooth(method = "lm", formula = "y ~ x", se = FALSE, color = "black") +
  geom_abline(
    intercept = 0, slope = 1, color = "gray",
    linetype = "dashed", size = 0.5
  ) +
  stat_poly_eq(
    aes(label = after_stat(
      paste0(
        "italic(y)~`=`~", round(b_0, 2), "+", round(b_1, 2), "*italic(x)",
        "*`,`~italic(R)^2~`=`~", round(r.squared, 2)
      )
    )),
    output.type = "numeric",
    parse = TRUE
  )