3

I want labels with superscripts in my legend. Furthermore, I want to construct the labels with paste function. I have figured out how to have a legend that uses my vector of values using paste. I have also used expression to get superscripts. But I can't use them together.

Here are my attempts:

A plot with the legend successfully plotting three legend items based on a vector of values but no superscript in legend.

#set-up
size=c(50, 100, 150)
paste(size, "km^2", sep=" ")
#output: paste function works
# "50 km^2"  "100 km^2" "150 km^2"

#plot sample graph
plot(x=c(1:10)*100, y=c(1:10)*10, col="red")
points(x=c(8:17)*50, y=c(1:10)*7, col="green")
points(x=c(8:17)*50, y=c(1:10)*12, col="blue")
#legend
legend(x = 'topleft', 
       legend = paste(size, "km^2", sep=" "),
       col = c("red", "green", "blue"), pch=19,bty = 'n', xjust = 1, cex=0.8)

And here I can print with superscripts on the graph but without paste.

#print with superscript
mtext(line=-4,adj=0,expression('km'^'2'*' size '))

FAILED GRAPHS

enter image description here

4
  • 1
    If you just need squares, why not use the Unicode character for square km² Commented Mar 9, 2018 at 21:04
  • @G5W Could you expand on that? I am not familar with Unicode characters and my google searching is not getting me anything that works out Commented Mar 9, 2018 at 21:14
  • 1
    You can cut and paste the character, either from my comment km² OR just google to find them. For example, Wikipedia has a page on Unicode subscripts and superscripts Just cut and paste the ones you need. x² x³ x⁴ x⁵ x⁶ x⁷ x⁸ x⁹ Paste it into your legend statement. Commented Mar 9, 2018 at 21:19
  • legend(x = 'topleft', legend = paste(size, 'km² size ', sep=" "), col = c("red", "green", "blue"), pch=19, bty = 'n', xjust = 1, cex=0.8) Commented Mar 9, 2018 at 21:24

1 Answer 1

4

You can create a vector of expression strings using paste and then parse them.

plot(x=c(1:10)*100, y=c(1:10)*10, col="red")
points(x=c(8:17)*50, y=c(1:10)*7, col="green")
points(x=c(8:17)*50, y=c(1:10)*12, col="blue")

#legend
legend(x = 'topleft', 
       legend = parse(text=paste(size, "*km^2~size")),
       col = c("red", "green", "blue"), pch=19, bty = 'n', xjust = 1, cex=0.8)

enter image description here

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

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.