aboutsummaryrefslogtreecommitdiff
path: root/txtPlot.tcl
diff options
context:
space:
mode:
authorEugeniy E. Mikhailov <evgmik@gmail.com>2018-05-10 23:44:03 -0400
committerEugeniy E. Mikhailov <evgmik@gmail.com>2018-05-10 23:47:40 -0400
commite9d4c779a3b9583e0e9de004df77650119e320d8 (patch)
tree6b7a1b8775fa984a581c6e89a7b4e7ed340b171a /txtPlot.tcl
parent60dc2f0475ac932d72a572c039da1078bd568b6c (diff)
downloadGradeBook-e9d4c779a3b9583e0e9de004df77650119e320d8.tar.gz
GradeBook-e9d4c779a3b9583e0e9de004df77650119e320d8.zip
offload text plotting to separate library
Diffstat (limited to 'txtPlot.tcl')
-rw-r--r--txtPlot.tcl81
1 files changed, 81 insertions, 0 deletions
diff --git a/txtPlot.tcl b/txtPlot.tcl
new file mode 100644
index 0000000..8fa9c71
--- /dev/null
+++ b/txtPlot.tcl
@@ -0,0 +1,81 @@
+#!/bin/sh
+# (C) 2018 by Eugeniy Mikhailov, <evgmik@gmail.com>
+# vim:set ft=tcl: \
+exec tclsh "$0" "$@"
+
+package require math::statistics
+
+proc data2txtPlot { data } {
+ # fixme: use buil-in min and max to get rid math::statistics dependence
+ set maxVal [::math::statistics::max $data ]
+ set minVal [::math::statistics::min $data ]
+ set diffVal [expr {$maxVal-$minVal}]
+ set chars {▁ ▂ ▃ ▄ ▅ ▆ ▇ █}; # 8 bars
+ if { $diffVal == 0 } {
+ set diffVal 1
+ set chars {▄}; # if all values are the same use mid bar
+ }
+ set barsNum [llength $chars];
+ foreach x $data {
+ # funky 1.1 are needed to convert it to floats
+ set cnt [expr { round((1.0*$x-$minVal)/(1.1*$diffVal)*(1.1*($barsNum-1.0))) }]
+
+ # safety check on counter value
+ set cnt [expr {min($cnt, ($barsNum-1))}]
+ set cnt [expr {max($cnt, 0)}]
+
+ set bar [lrange $chars $cnt $cnt]
+ lappend strPlot $bar
+ }
+ return [join $strPlot ""]
+}
+
+proc binInHistogram { x limits } {
+ # calculates which bin in histogram is occupied by data with value x
+ # limits of the histogram they are used the same way as in ::math::statistics::histogram
+ set cnt 0
+ foreach lim $limits {
+ if { $x < $lim } {
+ break;
+ }
+ incr cnt
+ }
+ return $cnt;
+}
+
+proc markNthBin { i } {
+ #set mark {█}
+ #set mark {╽}
+ set mark {╿}
+ #set space {▁}
+ set space {─}
+ set out {}
+ set cnt 0
+ set i [expr {max(0,$i)}]
+ while { $cnt < $i } {
+ lappend out $space
+ incr cnt
+ }
+ lappend out $mark
+ return [join $out ""]
+}
+
+# usage examples
+#
+#puts [ data2txtPlot {1 2 3 4 5 6 7 8} ]
+#puts [ data2txtPlot {1 2 3 4 5 6 7 8 7 6 5 4 3 2 1} ]
+
+#puts [ binInHistogram -10 {10 20 30}]
+#puts [ binInHistogram 15 {10 20 30}]
+#puts [ binInHistogram 25 {10 20 30}]
+#puts [ binInHistogram 35 {10 20 30}]
+#puts [ binInHistogram 30 {10 20 30}]
+#puts [ binInHistogram 10 {10 20 30}]
+
+#puts [ markNthBin 0 ]
+#puts [ markNthBin 1 ]
+#puts [ markNthBin 2 ]
+#puts [ markNthBin 10 ]
+
+
+# vim: ts=2 sw=2 foldmethod=indent: