0

I'd like to add multiple text labels to a plot that consist of an expression, that produces an italicised character, and a vector of values (stored in a data frame).

I can make this work with only one value using (for example) the following code:

plot.new()
axis(1)
axis(2)

text( c(0.5, 0.5), c(0.8, 0.4), 
expression(paste(italic(P),"-trend =", 0.01)) )

enter image description here

However, I can't manage to make this work when replacing 0.01 with a vector of values. For example, the following

plot.new()
axis(1)
axis(2)

text( c(0.5, 0.5), c(0.8, 0.4), 
expression(paste(italic(P),"-trend =", c(0.01, 0.001))) )

does not give the correct vector of labels but this:

enter image description here

Since the vector is inside expression(). How could I make this work? I'm not knowledgeable in this particular area and perhaps I've missed a more obvious way of doing it.

A similar question was posted here but I can't manage to extrapolate it to my case.

Joe
  • 8,073
  • 1
  • 52
  • 58

2 Answers2

1

You can swap expression for bquote which has a different use of italic and allows using .() to evaluate an object. I discovered this use here. Then I use a for loop as a workaround for the desired vectorized functionality.

plot.new(); axis(1); axis(2)

txt <- list(x = c(0.5, 0.5), y = c(0.8, 0.4), vals = c(0.01, 0.001))

for(i in 1:length(txt$vals)){
  text(x = txt$x[i], 
       y = txt$y[i], 
       labels = bquote(paste(italic("P"), "-trend = ", .(txt$vals[i]))))
}

example plot

Evan Friedland
  • 3,062
  • 1
  • 11
  • 25
1

@Evan's solution works fine but thanks to his answer and others found on SO I managed to vectorise it with sapply(), eliminating the need for a for loop.

plot.new()
axis(1)
axis(2)

plabs <- function(x) as.expression(bquote(italic(P)~ "-trend =" ~ .(x) ))
text(c(0.5, 0.5), c(0.8, 0.4), labels = sapply(c(0.01, 0.001), plabs))

This also produces the desired result.

Joe
  • 8,073
  • 1
  • 52
  • 58
  • 1
    Really nicely done. I had attempted this but failed and stopped before naming the function and using it inside. Looks great! +1 – Evan Friedland Sep 24 '18 at 06:47