R:以编程方式生成带有上标的绘图轴中断标签

R: Generate plot axis break labels with superscripts programmatically

我想制作带有上标的刻度标签,如以下示例中的 mylabels 所示。但是,我不想对它们进行手动编码,我希望它们达到 3^LEVELS,其中 LEVELS 是一个常数

library(ggplot2)

LEVELS = 4

mylabels = c(
  expression(paste(3^4,"= 81")),
  expression(paste(3^3,"= 27")),
  expression(paste(3^2,"= 9")),
  expression(paste(3^1,"= 3")),
  expression(paste(3^0,"= 1")))
mylabels
length(mylabels)


df=data.frame(x=runif(40),y=(runif(40)*10)%%5)
p = ggplot(df,aes(x,y))  + 
  geom_point() + 
  scale_y_continuous(breaks = 0:LEVELS, labels = mylabels)
p

硬编码版本完美运行。但我似乎无法以编程方式获取它。以下:

mylabels=c(paste("expression(paste(3^",LEVELS:0,'," = ',3^(LEVELS:0),'"))',sep=""))

未在图表中正确计算(例如,它在标签中写下单词 'expression' 等)。它创建:

[1] "expression(paste(3^4,\" = 81\"))" "expression(paste(3^3,\" = 27\"))" "expression(paste(3^2,\" = 9\"))" 
[4] "expression(paste(3^1,\" = 3\"))"  "expression(paste(3^0,\" = 1\"))" 

而我想要的是:

expression(paste(3^4, "= 81"), paste(3^3, "= 27"), paste(3^2, 
"= 9"), paste(3^1, "= 3"), paste(3^0, "= 1"))

搞砸了 collapse、noquote、eval、sprintf 等

您需要先将表达式向量构建为字符向量,然后使用parse(), which returns an expression vector correspondent to the input character vector. Building the character vector is best done with sprintf():

对其进行解析
mylabels <- parse(text=sprintf('paste(3^%d,\' = %d\')',LEVELS:0,3^(LEVELS:0)));
mylabels;
## expression(paste(3^4,' = 81'), paste(3^3,' = 27'), paste(3^2,' = 9'),
##     paste(3^1,' = 3'), paste(3^0,' = 1'))


其他提示:

1:当提供依赖于随机数生成的示例代码时,请在生成任何随机数之前调用set.seed()

2: expression() 函数是可变的,returns 是一个表达式向量,其元素对应于输入参数。因此你可以替换

c(
    expression(paste(3^4,"= 81")),
    expression(paste(3^3,"= 27")),
    expression(paste(3^2,"= 9")),
    expression(paste(3^1,"= 3")),
    expression(paste(3^0,"= 1"))
)

expression(
    paste(3^4,"= 81"),
    paste(3^3,"= 27"),
    paste(3^2,"= 9"),
    paste(3^1,"= 3"),
    paste(3^0,"= 1")
)

3: 避免对 c() 的冗余调用。你可以替换

c(paste("expression(paste(3^",LEVELS:0,'," = ',3^(LEVELS:0),'"))',sep=""))

paste("expression(paste(3^",LEVELS:0,'," = ',3^(LEVELS:0),'"))',sep="")