19

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.

nbro
  • 15,395
  • 32
  • 113
  • 196
Mateusz Kędzior
  • 193
  • 1
  • 1
  • 4

4 Answers4

30

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.

nbro
  • 15,395
  • 32
  • 113
  • 196
EDi
  • 13,160
  • 2
  • 48
  • 57
14
hist(data)
abline(v=mean(data),col="blue")
8

If you have data frames with more columns using of ggplot2 package is my preferred option:

ggplot (data, aes (x = colname)) + geom_vline(xintercept=mean(data$colname), color="red")

Colname is column in your data.frame for which you would like to plot the histogram and mean.

MartinK
  • 203
  • 2
  • 5
1

I ran into a problem where the mean line wasn't appearing, and I wasn't getting any error to help me figure out why. I realized that nothing was happening because I had some missing data, so the mean was calculated as NA. Adding na.rm = T to the mean() arg got me a real number, and the mean line appeared. It's a small oversight and a simple fix hardly worth writing about, but I'm posting it anyway in case it might save someone some grief.

hist(data$Defect.rate, 
 xlim = c(0, 1),
 col = "light blue")

abline(v = mean(data$Defect.rate, na.rm = T),
            col = "red",
            lwd = 2)
nusbaume
  • 27
  • 1
  • 1
  • 6