TMOTTM
TMOTTM

Reputation: 3391

Use Tex expression in R `main` label

I'm plotting a histogram in R and I want to include a $\bar{X}$ expression in the main argument of hist and combine it with the value of a dynamically calculated variable average.

x <- rnorm(100, 1, 1)
average <- mean(x)
hist(x, main=paste("Average $\bar{X}=", average))

That SO doesn't work and I spent hours trying to get it working with an expression statement or a substitute statement, both of which I dont find a case in the examples where the value of a variable is substituted in the text.

Upvotes: 1

Views: 124

Answers (2)

IRTFM
IRTFM

Reputation: 263451

Try:

hist(x, main=bquote(Average~bar(X)==.(average) )

bquote's main use is to "import-and-evaluate" named values from the global (or enclosing) environment(s) into an expression which would otherwise not be evaluating its tokens. You could add spaces to make the expression more readable but the parser ignores them:

 hist(x, main=bquote( Average ~ bar(X) == .( average ) )

If you need extra spaces use multiple tilde's: ~~~

It's rather interesting to look at the code for bquote (easy since it's not hidden):

bquote

Upvotes: 1

Dason
Dason

Reputation: 61953

This solution uses * to paste text and expressions and uses substitute to replace 'average' with the calculated value.

hist(x, main = substitute("Average "*bar(x)*" = "*average, list(average=average)))

Upvotes: 1

Related Questions