Register now and start sharing your code snippets.
-->
How to generate a histogram with Perl
Perl posted about 1 year ago by christian
I couldn’t find a histogram library for Perl, so I had to write my own.
Save the following code in histogram.pl:
1 use POSIX qw(ceil floor); 2 3 # No bugs, please 4 use strict; 5 use warnings; 6 7 # Perl doesn't have round, so let's implement it 8 sub round 9 { 10 my($number) = shift; 11 return int($number + .5 * ($number <=> 0)); 12 } 13 14 sub histogram 15 { 16 my ($bin_width, @list) = @_; 17 18 # This calculates the frequencies for all available bins in the data set 19 my %histogram; 20 $histogram{ceil(($_ + 1) / $bin_width) -1}++ for @list; 21 22 my $max; 23 my $min; 24 25 # Calculate min and max 26 while ( my ($key, $value) = each(%histogram) ) 27 { 28 $max = $key if !defined($min) || $key > $max; 29 $min = $key if !defined($min) || $key < $min; 30 } 31 32 33 for (my $i = $min; $i <= $max; $i++) 34 { 35 my $bin = sprintf("% 10d", ($i) * $bin_width); 36 my $frequency = $histogram{$i} || 0; 37 38 $frequency = "#" x $frequency; 39 40 print $bin." ".$frequency."\n"; 41 } 42 43 print "===============================\n\n"; 44 print " Width: ".$bin_width."\n"; 45 print " Range: ".$min."-".$max."\n\n"; 46 }
To generate a histogram for a set of data include the histogram subroutine and pass the desired width of the bins to the routine and the dataset as an array:
1 do('histogram.pl'); 2 3 histogram(10, (1,2,3,4,5,10,11,12,20,21,30));
The output of the above example is:
1 0 ##### 2 10 ### 3 20 ## 4 30 # 5 6 =============================== 7 8 Width: 10 9 Range: 0-3
The generated histogram tells us that there are: 5 numbers between 0-9, 3 between 10-19, 2 between 20-29, 1 between 30-39