Skip to content

Instantly share code, notes, and snippets.

@Rarst
Last active May 3, 2017 06:43
Show Gist options
  • Save Rarst/1175798 to your computer and use it in GitHub Desktop.
Save Rarst/1175798 to your computer and use it in GitHub Desktop.
"Nice numbers" implementation for pretty range of numerical labels on graph
<?php
// @link http://books.google.com/books?id=fvA7zLEFWZgC&pg=PA61&lpg=PA61#v=onepage&q&f=false
function nice_labels( $min, $max, $ticks = 5 ) {
$range = nice_number( $max, false );
$d = nice_number( $range / ( $ticks - 1 ) );
$graphmin = floor( $min / $d ) * $d;
$graphmax = ceil( $max / $d ) * $d;
$nfrac = max( array( - floor( log( $d, 10 ) ), 0 ) );
$output = array();
foreach ( range( $graphmin, $graphmax + 0.5 * $d, $d ) as $label ) {
$output[] = round( $label, $nfrac );
}
return $output;
}
function nice_number( $num, $round = true ) {
$exp = floor( log( $num, 10 ) );
$f = $num / pow( 10, $exp );
if ( $round ) {
if ( $f < 1.5 ) {
$nf = 1;
} elseif ( $f < 3 ) {
$nf = 2;
} elseif ( $f < 7 ) {
$nf = 5;
} else {
$nf = 10;
}
} else {
if ( $f <= 1 ) {
$nf = 1;
} elseif ( $f <= 2 ) {
$nf = 2;
} elseif ( $f <= 5 ) {
$nf = 5;
} else {
$nf = 10;
}
}
return $nf * pow( 10, $exp );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment