-1

I've searched this topic and tried a bunch of different things but still can't get my labels annotated in the right way.

On my label I want to show "R^2 = 0.81, p-value = 0.04, n = 50". So far I've tried:

df <- data.frame(x =  rnorm(10), y = rnorm(10))
stat <- paste("R^2= 0.81", "p-value= 0.04", "n= 50")
ggplot(df, aes(x = x, y = y)) + 
  geom_point() + 
  annotate("text", x = mean(df$x), y = mean(df$y), parse = T, label=stat)

This gave me the following error: Error in parse(text = as.character(lab)) : <text>:1:13: unexpected symbol 1: R^2= 0.81 p'

I've tried using expression instead of paste, like stat <- expression("R^2= 0.81", "p-value= 0.04", "n= 50"), but that gave a different error (Aesthetics must be either length 1 or the same as the data (1): label).

I've also noticed how some people used the apostrophe sign to solve problems with commas, so I've tried stat <- paste("R^2= 0.81","p-value= 0.04","n= 50") and that also creates an error. How can I get my label annotated right?

2
  • Does it work with parse = FALSE Apr 12, 2018 at 19:09
  • @RichardTelford It does! I thought I needed it to be true to display expressions but I guess I didn't understand how that command works...
    – Jen
    Apr 12, 2018 at 19:36

2 Answers 2

1
df <- data.frame(x =  rnorm(10), y = rnorm(10))
stat <- paste("R^2= 0.81", "p-value= 0.04", "n= 50")

ggplot(df, aes(x = x, y = y)) + geom_point() + 
   annotate("text", x = mean(df$x), y = mean(df$y), label=stat)
0
0

I just noticed that if I take out the parse command, I won't have the subscript in R2 depicted correctly. To avoid it I ended up using the following command:

df <- data.frame(x =  rnorm(10), y = rnorm(10))
ggplot(df, aes(x = x, y = y)) + geom_point() + 
   annotate("text", x = mean(df$x), y = mean(df$y), parse = TRUE, label = as.character(expression(R^{2}*" = 0.81; "*"p = 0.04; "*"n = 50")))

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.