Google Charts API Extended Encode Scaling

I’ve recently been playing with the Google Charts API for a project, and ran into a problem with graph scaling when using extended encoding.

The problem was that there was no scaling on the graph when using extended encoding, so values of the graph were plotted with the y-axis having a maximum value of 4095.

This meant that smaller values look insignificant on the graph, not to mention all the wasted space. The solution I came up with is to scale the data so it fills the chart appropriately.

The PHP code I came up with is below, and also extends on a function written by Ben Dodson.

    < ?php
 * Returns a scaled value.
 * @param    value     Int to scale
 * @param    max       Maximum int in array to calculate scale value
 * @param    scale     The int to scale value to
 * @return             Scaled value
 * @author             Alex McKenzie 
function scale_value($value, $max, $scale = 4095) {
	return ($value/$max) * $scale;

 * Retunrs an extended encoded string for use with Google Charts API.
 * Modified function - original by Ben Dodson (
 * @param    array     Array of values to encode
 * @param    scale     Whether to scale the values
 * @return             Extended encoded string
 * @author             Alex McKenzie [alex [at] alexmckenzie [dot] info]
function array_to_extended_encoding($array, $scale = 'yes') {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';

    // Scale values before encoding if required.
    if ($scale == 'yes') {
        $max = max($array);
        $scaled_array = array();
        foreach($array as $value) {
            array_push($scaled_array, scale_value($value, $max));
        $array = $scaled_array;

    // Encode values in array.
    $encoding = '';
    foreach ($array as $value) {
        $first = floor($value / 64);
        $second = $value % 64;
        $encoding .= $characters[$first] . $characters[$second];
    return $encoding;

Now using some sample data, we can see the difference scaling makes in the following two examples:

No scaling Scaling

The graphs above were generated with the following code:

    < ?php
$graph = array(200,300,200,250,350,150,100);
<img src="< ?=array_to_extended_encoding($graph, $scale = 'no')?/>" alt="No scalling" />
<img src="< ?=array_to_extended_encoding($graph)?/>" alt="Scalling" />

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.