How to put values on boxplot and control its width?
X<-c(1,2,,3,4,4,5,5,6,6,6,6,6,7)
I need to write values for min, max, 1st quartile, median and last quartile. How can I put it there?
The main values in a boxplot are minimum, first quartile, median, third quartile, and the maximum, and this group of values is also called five-number summary.
Q1 – quartile 1, the median of the lower half of the data set. Q2 – quartile 2, the median of the entire data set. Q3 – quartile 3, the median of the upper half of the data set.
The first step in constructing a box-and-whisker plot is to first find the median (Q2), the lower quartile (Q1) and the upper quartile (Q3) of a given set of data. You are now ready to find the interquartile range (IQR).
You can use horizontal = TRUE
get a horizontal boxplot and axes = FALSE
to remove the axes. staplewex = 1
sets the staple width the same as the box width
Then you can use fivenum
to return the statistics used to create the boxplot and use these as text labels, fiddling with the y
value until you have what you want
boxplot(X, horizontal = TRUE, axes = FALSE, staplewex = 1)
text(x=fivenum(X), labels =fivenum(X), y=1.25)
Note that i've inserted a 3
for the value missing in your example data X
The answer provided by mnel is perfect, assuming —as in the example— that there are not outliers. In that case, the lower and upper whiskers are then equal to the minimum and maximum. But, if there are outliers and we don't specify range = 0
in the boxplot function, we don't get the right values for the labels. Instead, we could use:
text(x=boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, y = 1.25)
Let's see an example:
Horizontally
X <- c(1,2,3,3,4,4,5,5,6,6,6,6,10,15)
boxplot(X, horizontal = TRUE, axes = FALSE, staplewex = 1)
text(x = fivenum(X), labels = fivenum(X), y = 1.25)
text(x = boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, y = 1.25)
Vertically
Switching the arguments for x and y inside text
.
boxplot(X, axes = FALSE, staplewex = 1)
text(y = boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, x = 1.25)
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