Skip to content

Instantly share code, notes, and snippets.

@haskellcamargo
Created August 20, 2015 13:34
Show Gist options
  • Select an option

  • Save haskellcamargo/8a6471c640f7f116c51a to your computer and use it in GitHub Desktop.

Select an option

Save haskellcamargo/8a6471c640f7f116c51a to your computer and use it in GitHub Desktop.
Update data
(ns pack.updatedata)
; Set the dimensions of the canvas / graph
(def margin (
js-obj "top" 30
"right" 20
"bottom" 30
"left" 50))
(def width (reduce - [600 (.-left margin) (.-right margin)]))
(def height (reduce - [270 (.-top margin) (.-right margin)]))
; Parse the date / time
(def parse-date
(.. js/d3
-time
(format "%d-%b-%y")
-parse))
; Set the ranges
(def x
(.. js/d3
-time
scale
(range (array 0 width))))
(def y
(.. js/d3
-time
scale
(range (array height 0))))
; Define the axes
(def x-axis
(.. js/d3
-svg
axis
(scale x)
(orient "bottom")
(ticks 5)))
(def y-axis
(.. js/d3
-svg
axis
(scale y)
(orient "left")
(ticks 5)))
; Define the line
(def valueline
(.. js/d3
-svg
line
(x (fn [d] (x (.-date d))))
(y (fn [d] (y (.-close d))))))
; Adds the svg canvas
(def svg
(.. js/d3
(select "body")
(append "svg")
(attr "width" (reduce + [width (.-left margin) (.-right margin)]))
(attr "height" (reduce + [height (.-top margin) (.-bottom margin)]))
(append "g")
(attr "transform"
(str "translate(" (.-left margin) "," (.-top margin) ")"))))
; Get the data
(.. d3
(svg "data.csv" (fn [error data]
(.forEach data (fn [d]
(set! (.-date d) (parse-date (.-date d)))
(set! (.-close) (.abs js/Math (.-close d)))))
; Scale the range of the data
(.domain x
(.extent js/d3 data (fn [d]
(.-date d))))
(.domain y
(.extent js/d3 data (fn [d]
(.-close d))))
; Add the valueline path
(.. svg
(append "path")
(attr "class" "line")
(attr "d" (valueline data)))
; Append the X Axis
(.. svg
(append "g")
(attr "class" "x axis")
(attr "transform" (str "translate(0," height ")"))
(call x-axis))
; Append the Y axis
(.. svg
(append "g")
(attr "class" "y axis")
(call x-axis)))))
; Update data section (Called from onclick)
(defn updatedata []
(.. js/d3
; Get the data again
(csv "data-lt.csv" (fn [error data]
(.forEach data (fn [d]
(set! (.-date d) (parse-date (.-date d)))
(set! (.-close d) (.abs js/Math (.-close d))))
; Scale the range of the data again
(.domain x
(.extent js/d3 data (fn [d]
(.-date d))))
(.domain y
(.extent js/d3 data (fn [d]
(.-close d))))
; Select the section we want to apply our changes to
(def svg
(.. js/d3
(select "body")
transition))
; Make the changes
(.. svg
(select ".line")
(duration 750)
(attr "d" (valueline data)))
(.. svg
(select ".x.axis")
(duration 750)
(call x-axis))
(.. svg
(select ".y.axis")
(duration 750)
(call y-axis)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment