如何将上标附加到变量以在ggplot轴中显示?

jcu*_*bic 2 r ggplot2

这是与此类似的问题如何使用上标与ggplot2

但我没有标签的硬编码值,而是在变量中有一个字符串,我需要将"mm ^ 3"附加到字符串并显示在其中ggplot.

我有这样的代码:

genericPlot <- genericPlot + labs(y = wrap(ylab, wrap.length))

#' Wrap
#' 
#' @param x character, values to be wrapped
#' @param width numeric, max number of characters
#' 
#' @return Wrapped x
wrap <- function(x, width) {
  sapply(
    X = x, 
    FUN = function(x) paste(strwrap(x, width = width), collapse = "\n"))
}
Run Code Online (Sandbox Code Playgroud)

我试过用这个:

paste(ylab, bquote(~mm^3))
Run Code Online (Sandbox Code Playgroud)

但这给了我2个元素的向量:

[1] "foo ~"    "foo mm^3"
Run Code Online (Sandbox Code Playgroud)

PoG*_*bas 5

你非常接近!而不是使用paste呼叫从自己的变量bquote使用.(VAR).

library(ggplot2)
ylab <- "foo"
myX  <- "bar" 
ggplot() + 
    ylab(bquote(.(ylab) *" ~ "* mm^3)) +
    xlab(bquote(.(myX) *" ~ "* kg^2))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述