Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

r - `bquote` is not interpreting the styling elements within a variable

I asked this question here, only to discover that it is actually not quite my problem.

The problem seems to be, that I need the variable ab and hello interpreted by bquote, but it doesn't work. How can I make bquote to interprete the variable content?

a <- "alpha"
b <- "beta"
ab <- "alpha[beta]"
hello <- "hello[hello]"
ggplot(data.frame(x=c(1), y=c(1)), aes(x, y)) + 
  geom_point() +
  labs(x = bquote(.(sym(a))[.(sym(b))]~.(sym(ab))~.(hello))) + ## will output the greek letters by "name"
  labs(y = bquote(alpha[beta]~hello[hello]))  ## the greek letter-names are replaces by the symbols

enter image description here

Edit:

With dipetkov's answer I did the following to define my label, which can then be simply used in ggplot's labs function. Note that the whole thing is wrapped in bquote while the the variable which needs styling is additional wrapped in .(parse_expr(paste(...)).

  ylab <- bquote(.(data$y_name[1])
                 ~.(parse_expr(paste(f(data$y_symbol[1]))))
                 ~"="~
                   "["*
                   .(data$y_unit[1])
                 *"]")
ggplot(...) + ... +
labs(y = ylab)

Edit 2: actually, the paste is unnecessary in my case.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Almost there... The tilde symbol, ~, doesn't print with either bquote or parse_expr (because in R it signifies a formula?). So I've substituted it with a dash, -.

library("rlang")
library("tidyverse")

ab <- "alpha[beta]"
hello <- "hello[hello]"

ggplot(data.frame(x = c(1), y = c(1)), aes(x, y)) +
  geom_point() +
  labs(x = parse_expr(paste(ab, "-", hello))) +
  labs(y = bquote(alpha[beta] ~ hello[hello]))

Created on 2019-11-04 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...