Draw Boxplot with Mean in R
In this article, we will discuss how to draw a boxplot with the mean in the R programming language.
Method 1: Using points() and text()
In this approach for drawing the boxplot with a mean value of the data on it, the user needs to call the boxplot() function with the required parameters for drawing the simple boxplot of the given data, and with this user needs to call the points() function to point out the mean value of every boxplot plotted and further with the help of the text() function with the required parameters it will be possible to get the mean value on the plot of the boxplot in the R programming language.
- Points(): This is a generic function to draw a sequence of points at the specified coordinates.
points(x, y = NULL, type = “p”, …)
- Text function helps to draw the strings given in the vector labels at the coordinates given by x and y.
text (x, y = NULL, labels = seq_along(x$x), adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, cex = 1, col = NULL, font = NULL, …)
Method 2: Using geom_boxplot() and stat_summary() from ggplot2 package
In this approach to drawing the boxplot with the mean, the user first needs to import and install the ggplot2 package to the R console as in this approach the used function is from the ggplot2 package, then the user needs to call the geom_boxplot() function with the required parameters which will lead to the normal plotting of the boxplot of the data provided and then further the user needs to call the stat_summary() which will find the mean of every boxplot and label it on the plot in the R programming language.
geom_boxplot() function is used to plot the Box and whiskers plot.
geom_boxplot( mapping = NULL, data = NULL, stat = “boxplot”, position = “dodge2”, …, outlier.colour = NULL, outlier.color = NULL,outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, outlier.stroke = 0.5, outlier.alpha = NULL, notch = FALSE,notchwidth = 0.5, varwidth = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE)
- stat_summary() function allows for tremendous flexibility in the specification of summary functions
stat_summary(mapping = NULL, data = NULL, geom = “pointrange”, position = “identity”, …)