Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use sub-/superscript and special characters in legend texts of R plots

I generate a plot for multiple datasets. Each of the datasets should get it's own legend, which might contain greek letters, plotmath symbols or sub and superscrition. I'd like to generate the legend-texts in a loop.

Bquote works fine, if there is only one legend text. If I try to add additinal legend texts, the plotmath-commads get lost,...

x <- 0:10
y1 = x * x
y2 = x * 10

plot (1,1, type="n", xlab=bquote(Omega), ylab="Y", las=1, xlim=range(x), ylim=range(y1, y2))
lines(x, y1, col=1, pch=1, type="b")
lines(x, y2, col=2, pch=2, type="b")

# generate legend texts (in a loop)
legend_texts = c(
  bquote(Omega^2)
  , bquote(Omega%*%10)
)
# Using a single bquote works fine:
#legend_texts = bquote(Omega^2)
#legend_texts = bquote(Omega%*%10)

legend(
  "topleft"
  , legend = legend_texts
  , col = c(1:2)
  , pch = c(1:2)
  , lty = 1
  )
like image 373
R_User Avatar asked Mar 08 '13 07:03

R_User


People also ask

How do you write subscript and superscript in R?

Subscripts and SuperscriptsTo indicate a subscript, use the underscore _ character. To indicate a superscript, use a single caret character ^ . Note: this can be confusing, because the R Markdown language delimits superscripts with two carets. In LaTeX equations, a single caret indicates the superscript.

How do you superscript a plot in R?

Superscript is “started” by the caret ^ character. Anything after ^ is superscript. The superscript continues until you use a * or ~ character. If you want more text as superscript, then enclose it in quotes.


2 Answers

Try this:

 legend_texts = expression(
   Omega^2, Omega*10)

 legend(
   "topleft"
   , legend = legend_texts
   , col = c(1:2)
   , pch = c(1:2)
   , lty = 1
   )

I could not tell if you wanted Omega^10 or Omega*10 or Omega%*%10 , but they all would produce acceptable plotmath expressions.

enter image description here

like image 80
IRTFM Avatar answered Oct 15 '22 07:10

IRTFM


Change "legend_texts" to:

# generate legend texts (in a loop)
legend_texts = c(
  as.expression(bquote(Omega^2))
  , as.expression(bquote(Omega%*%10))
)

From the help page for ?legend, the "legend" argument is described as:

a character or expression vector. of length ≥ 1 to appear in the legend. Other objects will be coerced by as.graphicsAnnot.

Output:

enter image description here

like image 45
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 15 '22 09:10

A5C1D2H2I1M1N2O1R2T1