f9d18a9526881f38e63883a93252f737a84e14c2
[barcat.git] / graph
1 #!/usr/bin/env perl
2 use 5.014;
3 use warnings;
4 use List::Util qw( max sum );
5
6 our $VERSION = '1.00';
7
8 use Getopt::Long '2.33';
9 sub podexit { require Pod::Usage; Pod::Usage::pod2usage(-exitval => 0, @_) }
10 GetOptions(\my %opt,
11         'width|w=i',
12         'usage|h' => sub { podexit() },
13         'help'    => sub { podexit(-verbose => 2) },
14 ) or exit 64;  # EX_USAGE
15 $opt{width} ||= $ENV{COLUMNS} || 80;
16
17 my @lines = readline or exit;
18 chomp for @lines;
19 my @values = map { s/^\h*([0-9]*)// and $1 } @lines;
20 my @order  = sort { $b <=> $a } @values;
21 my $lenval = 1 + int log($order[0]) / log 10;  # max string length
22 my $len    = 1 + max map { length } @lines;  # left padding
23 my $size   = ($opt{width} - $lenval - $len) / $order[0];  # bar multiplication
24
25 sub orderpos { ($order[$_[0]] + $order[$_[0] + .5]) / 2 * $size }
26 my @barmark;
27 $barmark[ sum(@values) / @values * $size ] = '=';  # average
28 $barmark[ orderpos($#order / 2) ] = '+';  # mean
29 defined and $_ = "\e[36m$_\e[0m" for @barmark;
30
31 for my $nr (0 .. $#lines) {
32         my $val = $values[$nr];
33         my $color =
34                 $val == $order[0] ? 32 : # max
35                 $val == $order[-1] ? 31 : # min
36                 90;
37         printf "\e[%sm", $color if $color;
38         printf "%*s", $lenval, $val;
39         print "\e[0m" if $color;
40         printf '%-*s', $len, $lines[$nr];
41         print $barmark[$_] // '-' for 1 .. $val * $size;
42         say '';
43 }
44
45 __END__
46
47 =head1 NAME
48
49 graph - append bar chart to input numbers
50
51 =head1 SYNOPSIS
52
53 B<graph> [<options>] [<input>]
54
55 cat ... | uniq -c | graph
56
57 =head1 DESCRIPTION
58
59 Each line starting with a number is given a bar to visualise relative sizes.
60
61 =head1 OPTIONS
62
63 =over
64
65 =item -w, --width=<columns>
66
67 Override the maximum number of columns to use.
68 Appended graphics will extend to fill up the entire screen.
69
70 =back
71
72 =head1 AUTHOR
73
74 Mischa POSLAWSKY <perl@shiar.org>
75
76 =head1 LICENSE
77
78 GPL3+.