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