2

In the example below, the variable holds the letter a. But the legend in legend just returns temp rather than a bolded a. How to make this work like it 'should'?

a <- 2
b <- 5
temp <- letters[1]
temp
plot(a,b)

legend("topleft", legend = c(as.expression(bquote(bold(get(temp)))),
                             as.expression(bquote(temp))))
2

2 Answers 2

3

Building off the answer from here: using bold in mtext on string coming from vector element

In order to tell bquote to evaluate a variable, instead of simply printing it as text, you need to wrap the term in .(), which causes it to instead evaluate it in the specified environment (given by the where argument).

temp <- 'a'
e <- new.env()
assign('temp','b',envir = e)
plot(2,5)
legend("topleft",
       legend = c(as.expression(
           bquote(bold(temp))),                 # No .(), `temp` is text
           bquote(bold(.(temp))),               # eval `temp` in parent.env
           bquote(bold(.(temp)), where = e)))   # eval `temp` in envir "e"

enter image description here

The help for ?bquote mentions this:

bquote quotes its argument except that terms wrapped in .() are evaluated in the specified where environment

Sign up to request clarification or add additional context in comments.

Comments

0

The two responses helped me to get to an answer for me. I asked the question about legend. I'm using the plot functions in the terra package and the answers didn't work in the legend option in terra::plot. But this code does if you replace x and y with the relevant coordinates in your plot.

text(x, y, cex = 1.5, (bquote(paste((bold(.(a)))))))

It's extremely ungainly to look at but trying to add say a space in that string of parentheses after the 'a' for clarity didn't seem to work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.