-
-
Save INDIAN2020/925651880550fd23e50869e0d8c382fb to your computer and use it in GitHub Desktop.
"Nice numbers" implementation for pretty range of numerical labels on graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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