-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?

Jen
  • 167
  • 9

2 Answers2

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)
cnicollet
  • 133
  • 7
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")))
Jen
  • 167
  • 9