0

I've looked through some other threads and tried using expression and bquote but without any luck. I'm a beginner with R and would appreciate help with this specific example. I've found the following code on another website and it is working for me, but I can't make the 2 in R2 a superscript.

This is the initial code:

ggplotRegression <- function (fit) {

require(ggplot2)

ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() +
    stat_smooth(method = "lm") +
    labs(title = paste("R2 = ",signif(summary(fit)$r.squared, 5),
                     "Intercept =",signif(fit$coef[[1]],5 ),
                     " Slope =",signif(fit$coef[[2]], 5),
                     " P =",signif(summary(fit)$coef[2,4], 5)))
}

ggplotRegression(lm(TOA_NDVI ~ Field_NDVI, data = NDVI_type))

This is one of the things I've tried:

ggplotRegression <- function (fit) {

require(ggplot2)

ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() +
    stat_smooth(method = "lm") +
    labs(title = paste(expression("R^2 *="),signif(summary(fit)$r.squared, 5)),
                     "Intercept =",signif(fit$coef[[1]],5 ),
                     " Slope =",signif(fit$coef[[2]], 5),
                     " P =",signif(summary(fit)$coef[2,4], 5)))
}

ggplotRegression(lm(TOA_NDVI ~ Field_NDVI, data = NDVI_type)) 

Any help would be very much appreciated. Thank you.

2
  • Welcome to SO! In the future, it is good practice to provide a reproducible dataset so others can debug your question. For example, if you run dput(NDVI_type) and paste the output in your question, others can easily access your data and run your code. As it is now, nobody can run this without having your data already. Commented Jan 11, 2023 at 13:10
  • Thanks Shawn, I will do this in future :) Commented Jan 14, 2023 at 15:39

1 Answer 1

3

You can use "bquote". Here is the code:

ggplotRegression <- function (fit) {
  
  require(ggplot2)
  
  ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() +
    stat_smooth(method = "lm") +
    labs(title = bquote(R^2== .(signif(summary(fit)$r.squared, 5))~
                          "Intercept = "~ .(signif(fit$coef[[1]],5 )) ~
                          " Slope = "~ .(signif(fit$coef[[2]], 5)) ~
                          " P = "~ .(signif(summary(fit)$coef[2,4], 5)) ))
}

ggplotRegression(lm(speed ~ dist, data = cars))

Here is the generated plot: enter image description here

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

1 Comment

Thank you so much Amin, that's exactly what I was trying to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.