Write x̄ (meaning average) in legend and how to prevent linebreak?

legend, legend-properties, plotmath, r

Solution

There are two issues here. The first is that this is handled using `?plotmath` in R. The operator you are looking for is `bar()`. This is not a function but markup that `plotmath` understands.

The second is that you need an expression in which `avg` is converted to its value. You need an expression because that is what `plotmath` works with. There are several solutions to this problem, but the one I use below is `bquote()`. You provide it an expression and anything wrapped in `.( )` will be converted its value by evaluating the thing inside the `.( )`.

Here is your code and a suitably modified `legend()` call:

test <- c(10,20,40,80,80)
avg <- mean(test)
avg <- format(avg,digits=2)

plot(test, xlab="x", ylab="y", pch = 4)
legend("topleft", legend = bquote(bar(x)*":" ~ .(avg)))

Do note that this will insert exactly what is in `avg`. You may need to do

avg <- round(avg)

or some other formatting fix to get something nice and presentable.

Problem

Good day! I am not that familiar to R so I'd be glad to get a little help. Assume I have the following minimal example: ``` test <- c(10,20,40,80,80) avg <- mean(test) avg <- format(avg,digits=2) plot(test, xlab="x", ylab="y", pch = 4) legend("topleft", legend= c("Average: ", avg)) ``` I'd like to write x̄ instead of "average" - wonder if this is event possible as it's not a regular symbol - merely a combination of two (letter plus overline). The other thing I'd like to get rid of is the line break after the word "Average (see arrow in graphic below):

Original source