Version 5 of Sparkline

Updated 2014-12-29 12:11:40 by dbohdan

Sparkline is a term Edward Tufte invented with for "small, high resolution graphics embedded in a context of words, numbers, images". On the Internet, however, the term has come to often mean rough text charts made with block characters, like this: ▁▂▃▅▂▇.

dbohdan 2014-12-29: This particular implementation was inspired by using one for Bash (sadly, incompatible with POSIX sh). It works in both Tcl 8.4+ and Jim Tcl.

namespace eval sparklines {
        namespace export create
        variable version 0.0.2
        variable ticks [list ▁ ▂ ▃ ▄ ▅ ▆ ▇ █]
        variable tickMax [expr {[llength $ticks] - 1}]
        proc create data {
                variable ticks
                variable tickMax
                set sorted [lsort -real $data]
                set min [lindex $sorted 0]
                set max [lindex $sorted end]
                if {$min == $max} {
                    # All data points are the same.
                    return [string repeat \
                            [lindex $ticks [expr {int($tickMax / 2)}]] \
                            [llength $data]]
                } else {
                    set result {}
                    foreach x $data {
                            set xNormalized [expr {
                                int($tickMax * ($x - $min) / ($max - $min))
                            }]
                            append result [lindex $ticks $xNormalized]
                    }
                }
                return $result
        }
}

puts [sparklines::create {1 5 22 13 53}] ;# ▁▁▃▂█
puts [sparklines::create {0 30 55 80 33 150}] ;# ▁▂▃▄▂█
puts [sparklines::create {9 13 5 17 1}] ;# ▄▆▂█▁
puts [sparklines::create {1 1 1 1}] ;# ▄▄▄▄

See also