Search code examples
rplotmath

use two variables and an expression within a plotmath()


I would like to do something like this:

Title<-paste(typis[which.panel],bquote(nu[x]==.(typas[which.panel])),sep="")

where typas is a vector of numbers and typis a vector of chars e.g.:

typas<-1:3
typis<-letters[1:3]

which.panel is an integer in 1:3 (this is because Title will change according to the panel)

and nu[x] should show as a plotmath object. but R ignores everything after the comma in the paste :(


Solution

  • It isn't immediately clear what you want, but if it is just an expression containing both bits of information, you don't need paste(), just include both bits in the bquote() call and separate them with one or more ~ depending on how much space you want. The key thing to note is that bquote() can take as many different .() as you want to include.

    typas <- 1:3
    typis <- letters[1:3]
    which.panel <- 2
    expr <- bquote(.(typis[which.panel]) ~~ nu[x]==.(typas[which.panel]))
    
    plot(1:10, main = expr)
    

    If you need a bit more formatting around the typis part of the expression (say to add a : if this is a panel label), then add this inside the relevant .():

    expr2 <-
      bquote(.(paste0(typis[which.panel], ":")) ~~ nu[x]==.(typas[which.panel]))
    plot(1:10, main = expr2)
    

    Of course, that could be done outside the expression:

    typis2 <- paste0(letters[1:3], ":")
    expr3 <- bquote(.(typis2[which.panel]) ~~ nu[x]==.(typas[which.panel]))
    plot(1:10, main = expr3)
    

    The three plots look like this:

    enter image description here

    The last two are essentially equivalent.