boxplot - How do I get box plot key numbers from an array in PHP? -
say have array values like:
$values = array(48,30,97,61,34,40,51,33,1);
and want values able plot box plot follows:
$box_plot_values = array( 'lower_outlier' => 1, 'min' => 8, 'q1' => 32, 'median' => 40, 'q3' => 56, 'max' => 80, 'higher_outlier' => 97, );
how in php?
function box_plot_values($array) { $return = array( 'lower_outlier' => 0, 'min' => 0, 'q1' => 0, 'median' => 0, 'q3' => 0, 'max' => 0, 'higher_outlier' => 0, ); $array_count = count($array); sort($array, sort_numeric); $return['min'] = $array[0]; $return['lower_outlier'] = $return['min']; $return['max'] = $array[$array_count - 1]; $return['higher_outlier'] = $return['max']; $middle_index = floor($array_count / 2); $return['median'] = $array[$middle_index]; // assume odd # of items $lower_values = array(); $higher_values = array(); // if have number of values, need special rules if ($array_count % 2 == 0) { // handle case averaging middle 2 items $return['median'] = round(($return['median'] + $array[$middle_index - 1]) / 2); foreach ($array $idx => $value) { if ($idx < ($middle_index - 1)) $lower_values[] = $value; // need remove both of values used median lower values elseif ($idx > $middle_index) $higher_values[] = $value; } } else { foreach ($array $idx => $value) { if ($idx < $middle_index) $lower_values[] = $value; elseif ($idx > $middle_index) $higher_values[] = $value; } } $lower_values_count = count($lower_values); $lower_middle_index = floor($lower_values_count / 2); $return['q1'] = $lower_values[$lower_middle_index]; if ($lower_values_count % 2 == 0) $return['q1'] = round(($return['q1'] + $lower_values[$lower_middle_index - 1]) / 2); $higher_values_count = count($higher_values); $higher_middle_index = floor($higher_values_count / 2); $return['q3'] = $higher_values[$higher_middle_index]; if ($higher_values_count % 2 == 0) $return['q3'] = round(($return['q3'] + $higher_values[$higher_middle_index - 1]) / 2); // check if min , max should capped $iqr = $return['q3'] - $return['q1']; // calculate inner quartile range (iqr) if ($return['q1'] > $iqr) $return['min'] = $return['q1'] - $iqr; if ($return['max'] - $return['q3'] > $iqr) $return['max'] = $return['q3'] + $iqr; return $return; }
Comments
Post a Comment