Login

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

Author:
simon
Posted:
February 21, 2009
Language:
JavaScript
Version:
Not specified
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. Django Collapsed Stacked Inlines by applecat 3 years ago
  2. Django Collapsed Stacked Inlines by mkarajohn 5 years, 2 months ago
  3. Dynamically adding forms to a formset. OOP version. by halfnibble 10 years, 10 months ago
  4. Convert multiple select for m2m to multiple checkboxes in django admin form by abidibo 12 years, 11 months ago
  5. Django admin inline ordering - javascript only implementation by ojhilt 13 years, 3 months ago

Comments

Please login first before commenting.