Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put values on a boxplot for median, 1st quartile and last quartile?

Tags:

r

boxplot

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?

like image 451
Manish Avatar asked Dec 19 '12 04:12

Manish


People also ask

How do you show the value of a boxplot?

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.

What is Q1 and Q3 in a box-and-whisker plot?

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.

What is Q1 Q2 Q3 in box plot?

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


2 Answers

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)

enter image description here

Note that i've inserted a 3 for the value missing in your example data X

like image 179
mnel Avatar answered Nov 10 '22 04:11

mnel


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)
  1. Incorrect valuestext(x = fivenum(X), labels = fivenum(X), y = 1.25)

enter image description here

  1. Correct values: text(x = boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, y = 1.25)

enter image description here

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)

enter image description here

like image 44
mpalanco Avatar answered Nov 10 '22 05:11

mpalanco