Adding a Google Charts plugin for views
Last modified: March 11, 2008 - 14:29
Here is some code that will let you add a Google Charts plugin for views. Couple of things I still need to work out:
a) sizing the chart - right now it is hardcoded
b) error handling
This code will help you display a chart assuming the first field is the x-axis and all the remaining fields are plotted on the y-axis. So the first field can be any field type, the remaining fields must be numeric fields..
<?php
function chartview_views_style_plugins() {
$items['chartviewplugin'] = array(
'name' => t('Chartview'),
'theme' => 'chartview_view',
'validate' => 'views_ui_plugin_validate_list',
'needs_fields' => true,
'weight' => 10,
);
return $items;
}
function theme_chartview_view($view, $nodes, $type) {
$fields = _views_get_fields();
$xaxis = array();
$data = array();
//need to flip the data array around..
$ys = array();
for ($i=1;$i<count($view->field);$i++) {
$ys[] = array();
}
foreach ($nodes as $node) {
$labels = array();
$r = 0;
foreach ($view->field as $field) {
if (!$r) {
$x = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view);
$xaxis[] = strip_tags($x);
}
else {
$y = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view);
$ys[$r-1][] = $y !='' ?$y:-1;
$labels[] = $field['label'];
}
$r++;
}
}
foreach ($ys as $y) {
$data[] = implode(',', $y);
}
$chart_size = "400x250";
//plot it now..
return '<img src="http://chart.apis.google.com/chart?chs='. $chart_size .'&chd=t:' . implode('|', $data) .'&cht=lc&chxt=x,y&chxl=0:|'. implode("|", $xaxis) .'|1:||'. $labels[0] .'" alt="'. views_get_title($view, $type) .'"/>';
}