I'm trying to create a list of labels that contain italics. I can do it with "expression" like this, and when I put them on a plot (by adding a legend as an example, but I'll use them different ways), it all works nicely.
sp.names=c(expression(paste("species ",italic("one")," sp.")),
expression(paste("species ",italic("two")," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)
But instead of specifying the words in the label directly in the code, I want to call them from cells in a dataframe (because there are a lot of them and they change depending on my underlying data). But when I try and specify which dataframe cell I want, it doesn't print the labels correctly (see below). Perhaps there is a different way for me to call the cell that I want that the "expression" function will recognise?
df=data.frame(V1=c("species","species","species"),V2=c("one","two","three"))
sp.names=c(expression(paste(df$V1[1],italic(df$V2[1])," sp.")),
expression(paste(df$V1[2],italic(df$V2[2])," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)
CodePudding user response:
Use substitute
, it substitutes variables in expressions.
sp.names=c(substitute(V1 ~ italic(V2) ~ "sp.", df[1,]),
substitute(V1 ~ italic(V2) ~ "sp.", df[2,]))
I also removed the unneeded paste
(which has a different meaning within plotmath) and replaced it with ~
for increased readability.
CodePudding user response:
Give bquote
a shot.
sp.names <- c(bquote(.(df$V1[1])~italic(.(df$V2[1]))~" sp."),
bquote(.(df$V1[2])~italic(.(df$V2[2]))~" sp."))
plot(1:10)
legend("topleft", legend=sp.names)