compbiostats
compbiostats

Reputation: 961

Pasting value into R plot title

I would like to paste the value of the mean in a plot title using the title() function.

e.g. title("My plot \n mean = mean(x)")

where x is a numeric vector of observations.

I know how to do this using plot(main = " ... ", ). Simply use paste() or substitute(expression()); however, this doesn't seem work with the title() function.

Any ideas?

Upvotes: 2

Views: 5818

Answers (2)

kangaroo_cliff
kangaroo_cliff

Reputation: 6222

Answer by @MarcoSandri is correct. The correct way of using the example codes you have written are,

title(main= paste("My plot \n mean =", mean(x)))

and

avg <- mean(x)
title(paste("My Plot \n Mean = ", avg))

Upvotes: 5

Marco Sandri
Marco Sandri

Reputation: 24252

See this example where title works correctly:

set.seed(1)
x <- rnorm(30)

txt <- paste("Mean =", round(mean(x),3) )   

plot(x)
title(main=txt)

enter image description here

Upvotes: 3

Related Questions