ggplot 使用粘贴意外符号注释标签错误

ggplot annotate label error with paste unexpected symbol

我搜索了这个主题并尝试了很多不同的方法,但仍然无法以正确的方式注释我的标签。

我想在我的标签上展示 "R^2 = 0.81, p-value = 0.04, n = 50"。到目前为止我已经尝试过:

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)

这给了我以下错误:Error in parse(text = as.character(lab)) : <text>:1:13: unexpected symbol 1: R^2= 0.81 p'

我试过使用 expression 而不是 paste,例如 stat <- expression("R^2= 0.81", "p-value= 0.04", "n= 50"),但出现了不同的错误 (Aesthetics must be either length 1 or the same as the data (1): label)。

我也注意到有些人如何使用撇号来解决逗号问题,所以我尝试了 stat <- paste("R^2= 0.81","p-value= 0.04","n= 50") 并且这也会产生错误。我怎样才能正确注释我的标签?

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)

我刚刚注意到,如果我去掉parse 命令,我将无法正确显示R2 中的下标。为了避免这种情况,我最终使用了以下命令:

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")))