Highcharts Boxplots How to get five point summary?

2.6k views Asked by At

I want to use HighCharts to create boxplots. As I can see in the docs I need to already provide Highcharts with the required five-point-summary, i.e., min, max, q1, q3, median values for creating the boxplot.

Given an arbitrary-length array constisting of numbers, how can I calculate these five numbers efficiently? Is there a quick means in JS to do so?

1

There are 1 answers

6
jlbriggs On BEST ANSWER

Although you have a solution for doing it server side, I took a few minutes to convert my PHP solution to a Javascript solution, to address the initial question.

step 1) function to calculate percentiles:

//get any percentile from an array
function getPercentile(data, percentile) {
    data.sort(numSort);
    var index = (percentile/100) * data.length;
    var result;
    if (Math.floor(index) == index) {
         result = (data[(index-1)] + data[index])/2;
    }
    else {
        result = data[Math.floor(index)];
    }
    return result;
}
//because .sort() doesn't sort numbers correctly
function numSort(a,b) { 
    return a - b; 
} 

step 2) wrapper to grab min, max, and each of the required percentiles

//wrap the percentile calls in one method
function getBoxValues(data) {
    var boxValues = {};
    boxValues.low    = Math.min.apply(Math,data);
    boxValues.q1     = getPercentile(data, 25);
    boxValues.median = getPercentile(data, 50);
    boxValues.q3     = getPercentile(data, 75);
    boxValues.high   = Math.max.apply(Math,data);
    return boxValues;
}

step 3) build a chart with it

example:

[[edit]]

A quick update that contemplates outliers: