1

How can i write H2o in the title of a plot?

Thanks to this hint I can include a plain chemical formula in the headline with

plot(main=expression(H[2]*O),0)

The real formulas here are a bit more complicate and i want to abbreviate them and add these to the text, where needed. But this fails:

h2o <- expression(H[2]*O)
plot(main=paste(h2o, "in the air"),0) # paste fails here :(
Community
  • 1
  • 1
Jonas Stein
  • 6,826
  • 7
  • 40
  • 72

2 Answers2

2

Here is an approach that will let you have the chemical formula in a variable.

# note that .formula is either an expression or a character
# string that would define a valid expression
maketitle <- function(.formula, .other){
  .expression <- sprintf('%s ~ "%s"',as.character(.formula), .other)
  evalq(parse(text = .expression))
}


f <- expression(H[2]*O)
o <- 'blah blah'

plot(1:10, main = maketitle(f, o))

Remembering the perils of eval(parse(text = ...)),

Personally I have never regretted trying not to underestimate my own future stupidity. -- Greg Snow (explaining why eval(parse(...)) is often suboptimal, answering a question triggered by the infamous fortune(106)) R-help (January 2007

mnel
  • 113,303
  • 27
  • 265
  • 254
1

You want

plot(1:10, main = expression(H[2] * O ~ "in the air"))

Or

plot(1:10, main = expression(H[2] * O ~ "in" ~ the ~ air))

(The in needs to be quoted because it is part of the syntax of R that the parser captures first, as in for(i in 1:10).)

The important point is the x ~ y notation places x and y next to one another with separation. Do read ?plotmath!

The main point though is that whatever you supply here needs to be an expression as returned by expression(). Generally you don't need paste() inside an expression as you can include character strings in an expression for plotmath.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453