Search code examples
rplotlabelexpressionfigure

Use of expression in combination with indicator variable for plot labels


I am creating multiple plots in a loop, where I have different labels stored in a list. This is easy enough to do with paste:

i<-1
plot(1,1)
legend("topright", paste("V = ", i))

However, I also wish to have subscripts, so am using the expression function:

plot(1,1)
legend("topright", expression("V"[accurate]*" = "))

But when I attempt to combine paste and expression, i no longer returns the value it refers to:

plot(1,1)
legend("topright", paste(expression("V"[accurate]*" = "), i))

I have tried multiple different ways of writing out the above, but am never able to get the subscript and '1' returned.

Perhaps using paste and expression together is not the correct way to go about this.


Solution

  • I believe with as.expression and bquote you can do the following:

    legend("topright", as.expression(bquote("V"[accurate]*" = "*.(i))))
    

    With bquote(), whatever is wrapped in .( ) will be replaced with the value of the named object.