Skip to content

Instantly share code, notes, and snippets.

@grantm
Created March 13, 2012 20:50
Embed
What would you like to do?
ChartImage.pm
# A quick hack for demoing using App::p to produce graphs from the command-line
# using Perl 1-liners.
#
# E.g.: to look through an Apache access log file and produce a bar graph of
# requests by hour of the day (00-23):
#
# p -nE 'm{/2012:(\d\d)} && $tally{$1}++ }{ S ChartImage->bar_url(data => \%tally, size => "700x300")' access.log
#
# Use it, copy it, sell it, claim it as your own - I don't care :-)
#
# -- Grant McLean <grant@cpan.org>
package ChartImage;
use strict;
use warnings;
use URI;
use Carp;
use List::AllUtils qw(max);
my $chart_base_url = 'https://chart.googleapis.com/chart';
my @palette = qw(
F8D753 5C9746 3E75A7 7A653E E1662A 74796F C4384F
F3C01C 3D8128 205F9A 63522B DC5313 5D645A BC1C39
);
sub pie_url {
my($class, %args) = @_;
my $data = $args{data} or croak "No 'data' supplied for chart";
my @labels = sort { $data->{$b} <=> $data->{$a} } keys %$data;
my @values = map { $data->{$_} } @labels;
my $i = 0;
my @colours = map { $palette[ $i++ % 14 ] } @labels;
my %opt = (
cht => 'p',
chs => $args{size} || '600x450',
chd => 't:' . join(',', @values),
chl => join('|', @labels),
chco => join('|', @colours),
);
$opt{chtt} = $args{title} if $args{title};
my $url = URI->new($chart_base_url);
$url->query_form(%opt);
return $url->as_string;
}
sub bar_url {
my($class, %args) = @_;
my $data = $args{data} or croak "No 'data' supplied for chart";
my @labels = sort keys %$data;
my @values = map { $data->{$_} } @labels;
my $max = max(@values);
my $inc =
my $i = 0;
my @colours = map { $palette[ $i++ % 14 ] } @labels;
my %opt = (
cht => 'bvs',
chs => $args{size} || '600x450',
chd => 't:' . join(',', @values),
chds => "0,$max",
chxt => 'x,y',
chxr => "1,0,$max",
chxl => '0:' . join('|', @labels),
chco => 'bbbbff',
);
$opt{chtt} = $args{title} if $args{title};
my $url = URI->new($chart_base_url);
$url->query_form(%opt);
return $url->as_string;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment