[R] How do you add the x-bar (mean of x) symbol and show a calculated mean in the title of a histogram?

Rolf Turner r.turner at auckland.ac.nz
Sat Oct 12 07:23:00 CEST 2013


On 10/12/13 11:39, Emily Jean Fales wrote:
> I am trying to get the calculated mean and the symbol of x-bar to show in
> the title of multiple histograms in R. Here is the code I have for one of
> the histograms:
>   hist(outcome[,11], main= "Heart Attack (expression(bar(x))) =
> (mean(outcome[,11]))", xlab ="30-day Death Rate", xlim = c(min(hist_min),
> max(hist_max)))
>
> but the symbol will not sow up in the title just the words I have typed
> do...I am not a programmer and new to R (obviously), so any help is
> appreciated!

You are being confronted with the mysteries of plotmath() which are 
opaque to us
ordinary mortals.  My approach is to remember vaguely a few tricks and 
then invoke
these tricks in a hammer-and-hope manner until something works.

For your problem the main trick is to use bquote() and the ".()" 
function.  Oh, yeah.
And paste the literal bit, i.e. "Heart Attack" onto the mathematical 
bit.  E.g.:

set.seed(42)
xxx <- rnorm(300,10,2)
hist(xxx,main=bquote(paste("Heart Attack  ", bar(x) == .(mean(xxx)))))

There are probably better ways.  And don't ask me for an explanation; it 
just seems
to work.

HTH

     cheers,

     Rolf Turner



More information about the R-help mailing list