在 ggplot 中使用 geom_text() 添加带有希腊字母的方程

问题描述

我有一个小数据框,我想用希腊字母在其中添加一个方程

library(tidyverse)
Beta  <- c( 1.53,1.36,1.24,1.17,1.06,0.92,0.84,0.76,0.63,0.48)
Sigma <- c( 0.49,0.43,0.39,0.37,0.33,0.29,0.27,0.24,0.20,0.17)
df    <- data.frame(Beta,Sigma)

然后,我使用以 Adding equations to ggplots in R 为模型的以下代码绘制 Sigma 与 Beta 的关系图:

ggplot(df,aes(x = Beta,y = Sigma)) +
  geom_point() + 
  geom_smooth(method='lm',formula = y ~ x,se = FALSE,size = 0.6,color = "gray20") +
  ylab("Standard Deviation") +  
  geom_text(aes(1.0,0.2,label=(paste(expression("sigma = 0.33 beta "*"")))),parse = TRUE) 

这有效,并在我的情节中为我提供了文本字符串“sigma = 0.33 beta”,但我真正想要的是希腊字母 mu 和 sigma,而不是 mu 和 sigma 这两个词。将表达式更改为 "$\sigma = 0.33 \beta "*""$(或它的变体)只会给我一个错误Error: '\s' is an unrecognized escape in character string starting ""$\s" 使用 geom_text() 向绘图添加希腊字母(或一般符号)的正确语法是什么?我试过 ?plotmath 似乎表明 alphabeta显示为希腊符号,但它们显然没有。

提前致谢

托马斯飞利浦

解决方法

当绘图坐标或任何其他美学元素不依赖于数据时,就不需要 aes()。下面的 geom_text 就是这种情况,它的参数都是常量。并且也不需要解析要绘制为文本标签的表达式。

ggplot(df,aes(x = Beta,y = Sigma)) +
  geom_point() + 
  geom_smooth(method='lm',formula = y ~ x,se = FALSE,size = 0.6,color = "gray20") +
  ylab("Standard Deviation") +  
  geom_text(x = 1.0,y = 0.2,label = expression(sigma == "0.33" ~ beta^"*"))

enter image description here