Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add the mean value to a histogram in R?

I would like to plot a histogram with mean (average) value on it (e.g. we could mark it with a blue and bold line).

I tried to do it using plot command, but even if I set the parameter add=TRUE it didn't work.

like image 427
Mateusz Kędzior Avatar asked Jul 02 '11 15:07

Mateusz Kędzior


People also ask

How do you add a mean line in R?

In the R Language, we can do so by creating a mean vector by using the group_by() and summarise() function. Then we can use that mean vector along with the geom_hline() function of the ggplot2 package to create a line by the mean point colored by the group.


1 Answers

You can use abline() to add lines to a plot:

x <- rnorm(100)
mx <- mean(x)
hist(x)
abline(v = mx, col = "blue", lwd = 2)

Have also a look at ?par for graphic parameters (like col and lwd).


In general, you can also plot lines using lines():

x <- rnorm(100, mean = 10)
mx <- mean(x)
hist(x)
lines(c(mx,mx), c(0,15), col = "red", lwd = 2)
lines(c(10, 11.5), c(0, 10), col = "steelblue", lwd = 3, lty = 22)
text(mx, 18 , round(mx, 2))
text(mx, 12 , "big", cex = 5)

where text() is used for adding text. The argument cex describes the "character expansion factor".

Also, have a look at Quick-R for an overview of basic plotting with R.

like image 62
EDi Avatar answered Sep 30 '22 17:09

EDi