Search code examples
rplotboxplotmedianiqr

How to obtain values (e.g. median) from a boxplot in r?


I’ve plotted a boxplot for PM2.5 levels per year.

Boxplot(PM2.5~year, data=subset(dat, hour==12), las=1)

How can I extract values such as the median from the boxplots?


Solution

  • The default boxplot function returns summaries invisibly, you just have to assign it to a variable:

    res <- boxplot(Sepal.Length ~ Species, data=iris)
    

    Within res there exists an element stats:

    > res$stats
         [,1] [,2] [,3]
    [1,]  4.3  4.9  5.6
    [2,]  4.8  5.6  6.2
    [3,]  5.0  5.9  6.5
    [4,]  5.2  6.3  6.9
    [5,]  5.8  7.0  7.9
    

    These are quartile summaries of the boxes. The median is the middle one, so:

    > res$stats[3,]
    [1] 5.0 5.9 6.5