Add borders and x-axis labels

This commit is contained in:
Dimitri Lozeve 2021-04-29 21:14:23 +02:00
parent 46d5d0a90d
commit 60fd538a67
4 changed files with 39 additions and 27 deletions

BIN
demo.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Before After
Before After

View file

@ -11,4 +11,4 @@
(ys1 (map cos xs))
(ys2 (map (lambda (x) (/ 1 (+ 0.5 x))) xs))
(ys3 (map (lambda (x) (sin (* 2 x))) xs)))
(displayln (line-plot [xs ys1 ys2 ys3]))))
(displayln (line-plot [xs ys1 ys2 ys3] xlabel: "time"))))

View file

@ -53,8 +53,7 @@
(char-color (indexf (lambda (x) (or (char=? (car x) #\newline)
(char>? (car x) #\)))
characters colors)))
(if char-color
(str (graphics-style [(cadr char-color)])
(car char-color)
(graphics-style))
#\)))))
(match char-color
(#f " ")
([#\newline col] "\n")
([c col] (str (graphics-style [col]) c (graphics-style))))))))

View file

@ -20,24 +20,37 @@
#t))
canvas)
(def (line-plot lsts (colors +default-colors+) width: (width 160) height: (height 80))
(canvases->string
(match lsts
([ys] [(draw-canvas (iota (length ys)) ys
(scale-fn 0 (length ys))
(scale-fn (apply min ys) (apply max ys))
width: width height: height)])
([xs ys] [(draw-canvas xs ys
(scale-fn (apply min xs) (apply max xs))
(scale-fn (apply min ys) (apply max ys))
width: width height: height)])
([xs . yss]
(let* ((x-scale-fn (scale-fn (apply min xs) (apply max xs)))
(all-ys (flatten yss))
(min-ys (apply min all-ys))
(max-ys (apply max all-ys))
(y-scale-fn (scale-fn min-ys max-ys)))
(for/collect ((ys yss))
(draw-canvas xs ys x-scale-fn y-scale-fn
width: width height: height)))))
colors))
(def (line-plot lsts (colors +default-colors+)
width: (width 160) height: (height 80) borders: (borders #t)
xlabel: (xlabel #f))
(def canvases
(match lsts
([ys] [(draw-canvas (iota (length ys)) ys
(scale-fn 0 (length ys))
(scale-fn (apply min ys) (apply max ys))
width: width height: height)])
([xs ys] [(draw-canvas xs ys
(scale-fn (apply min xs) (apply max xs))
(scale-fn (apply min ys) (apply max ys))
width: width height: height)])
([xs . yss]
(let* ((x-scale-fn (scale-fn (apply min xs) (apply max xs)))
(all-ys (flatten yss))
(min-ys (apply min all-ys))
(max-ys (apply max all-ys))
(y-scale-fn (scale-fn min-ys max-ys)))
(for/collect ((ys yss))
(draw-canvas xs ys x-scale-fn y-scale-fn
width: width height: height))))))
(def canvases-str (canvases->string canvases colors))
(def hor-size (u8vector-length (vector-ref (car canvases) 0)))
(def plot (if borders
(str
" ┌" (make-string (+ 2 hor-size) #\─) "┐\n │ "
(string-subst canvases-str "\n" " │ \n │ ")
(make-string (+ 1 hor-size) #\ )
"│\n └" (make-string (+ 2 hor-size) #\─) "┘\n")
canvases-str))
(if xlabel
(str plot (make-string (quotient hor-size 2) #\ ) xlabel "\n")
plot))