开发者

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.


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.


hist(data)
abline(v=mean(data),col="blue")


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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜