Write x̄ (which means average) in the legend and how to prevent discord?

Good afternoon!

I am not so familiar with R, so I would be happy to receive a little help.

Suppose 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 would like to write x̄ instead of "average" - to ask if this event is possible, since this is not an ordinary character - it's just a combination of two (letter superscript line).

Another thing I would like to get rid of is line break after the word "Average (see arrow in the image below):

Output

+4
source share
1 answer

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

Secondly, you need an expression in which avg converted to its value. You need an expression because this is what plotmath works plotmath . There are several solutions to this problem, but I am using bquote() below. You provide it with an expression, and everything that is wrapped in .( ) Transforms its value, evaluating the subject inside .( ) .

Here is your code and the correspondingly 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))) 

Note that this accurately inserts what is in avg . You may need

 avg <- round(avg) 

or another formatting fix to get something nice and presentable.

+8
source

Source: https://habr.com/ru/post/1445519/


All Articles