Skip to content

Instantly share code, notes, and snippets.

@joastbg
Last active June 2, 2018 11:18
Show Gist options
  • Save joastbg/8550833 to your computer and use it in GitHub Desktop.
Save joastbg/8550833 to your computer and use it in GitHub Desktop.
Basic plotting done in Clojure
;; Helper function to plot data
(defn drawStuff [#^java.awt.Graphics g w h data ]
(let [pad 20
xinc (/ (- w (* 2.0 pad)) (count data))
ymin (apply min data)
scale (/ (- h (* 2.0 pad)) (- (apply max data) ymin))
xdata (take (count data) (iterate inc 0))]
(defn transform-x [x] (+ pad (* x xinc)))
(defn transform-y [y] (+ (- h pad (* scale y)) (* ymin scale)))
(doseq [[x y] (map list (iterate inc 0) data)]
(.fillOval g (- (transform-x x) 3) (- (transform-y y) 3) 6 6))
(doto g
(.drawPolyline (int-array (map transform-x xdata))
(int-array (map transform-y data)) (count data))
(.drawLine 20 20 20 (- h 20))
(.drawLine 20 (- h 20) (- w 20) (- h 20)))))
(defn plot [data]
(let [panel (proxy [javax.swing.JPanel] []
(paintComponent [g]
(proxy-super paintComponent g)
(let [width (proxy-super getWidth)
height (proxy-super getHeight)]
(doto g
(drawStuff width height data)))))]
(doto (javax.swing.JFrame. "Plot data in JPanel")
(.setContentPane panel)
(.setSize 800 600)
(.show))))
(-> [1 4 5 6 10 2 -3 1 2 3 0.3] plot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment