简体   繁体   中英

How to parse an expression to be used as a label (ggplot2)

I created a function to make a ggplot2 graphic. In this function, I am passing a string as a variable that I would like to use as the y-label. To do so, I am using parse() . The following works fine:

library(ggplot2)

ylab <- "xxx ~(x^2)"

plot_fun <- function(ylab) {
  ggplot() +
    ylab(parse(text = ylab))
}

plot_fun(ylab)

In the next example, I have an error because of the % sign.

ylab <- "xxx ~(%)"
plot_fun(ylab)
#> Error in parse(text = ylab): <text>:1:7: unexpected input
#> 1: xxx ~(%)
#>           ^

Is there a better way to parse the string?

Created on 2020-09-17 by the reprex package (v0.3.0.9001)

Put backticks in between the "%" the symbol :

ylab <- "xxx ~(`%`)"
plot_fun(ylab)

Try this formating your labels with expression() if necessary:

ylab <- expression(xxx ~"(%)")
plot_fun(ylab)

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM