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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With