Login

generateChart() for creating a Google Chart API pie chart from JavaScript

Author:
simon
Posted:
February 21, 2009
Language:
JavaScript
Version:
Not specified
Tags:
javascript googlechartapi piechart graphs
Score:
0 (after 0 ratings)

I ended up not needing this (there's a good reason it's in JS and not Python, but most people would probably want to do this server-side instead) but I'm stashing it here in case I need it later.

It uses jQuery for the .each() method - which is very easy to replace if you need it to work without that dependency.

Usage:

var src = generateChart({
    "foo": 5,
    "bar": 3,
    "baz": 6
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function generateChart(figures) {
    // figures is an object mapping labels to numbers
    var cht = 'p'; // Chart type: pie
    var chs = '460x200'; // Image dimensions
    var chd = []; // Chart data
    var chl = []; // Corresponding labels
    var min = 0;
    var max = 0;
    $.each(figures, function(label, value) {
        chl[chl.length] = label;
        chd[chd.length] = value;
        max = Math.max(max, value);
    });
    if (max == 0) {
        return ''; // Don't attempt to render blank graphs
    }
    var chds = '' + min + ',' + max; // Chart data scale
    chd = 't:' + chd.join(',');
    chl = chl.join('|');
    return 'http://chart.apis.google.com/chart?' + [
        'cht=' + cht,
        'chs=' + chs,
        'chd=' + chd,
        'chl=' + chl,
        'chds=' + chds
    ].join('&');
}

More like this

  1. Last.fm Charts by sedden 7 years, 2 months ago
  2. Generate QR Code image for a string by johnnoone 6 years, 4 months ago
  3. Publishing service endpoint uri to javascript by dberansky 5 years, 2 months ago
  4. Google Charts Templatetags (Python) by justquick 7 years, 2 months ago
  5. Google Charts Templatetags (HTML) by justquick 7 years, 4 months ago

Comments

Please login first before commenting.