我想使用HighCharts创建箱图。正如我在docs中所看到的,我需要为Highcharts提供所需的五点汇总,即min,max,q1,q3,用于创建箱线图的中值。
给定一个由数字组成的任意长度数组,如何有效地计算这五个数字? JS中有快速的方法吗?
答案 0 :(得分:6)
虽然你有一个服务器端的解决方案,但我花了几分钟时间将我的PHP解决方案转换为Javascript解决方案,以解决最初的问题。
步骤1)计算百分位数的函数:
//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;
}
步骤2)包装器以获取最小值,最大值和每个所需的百分位数
//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;
}
步骤3)用它构建图表
示例:
<强> [[编辑]] 强>
考虑异常值的快速更新: