Skip to content

Instantly share code, notes, and snippets.

@mrkurt
Created January 16, 2012 20:10
Show Gist options
  • Save mrkurt/1622733 to your computer and use it in GitHub Desktop.
Save mrkurt/1622733 to your computer and use it in GitHub Desktop.
class Sparkline
constructor : (elem, @data, @opts)->
@opts ||= {}
_.extend(@opts, Sparkline.defaults)
@width = $(elem).width()
@height = $(elem).height()
@graph = d3.select(elem).append("svg:svg").attr("width", @width).attr("height", @height)
@data ||= [0]
@setScale()
@line = d3.svg.line().interpolate(@opts.interpolate)
@line.x (d, i)=>
@scaleX(i)
@line.y (d)=>
@scaleY(d)
@path = @graph.append("svg:path").attr("d", @line(@data))
redraw : ->
@graph.selectAll("path")
.data([@data])
.attr("transform", "translate(" + @scaleX(1) + ")")
.attr("d", @line)
.transition()
.ease(@opts.ease)
.duration(@opts.duration)
.attr("transform", "translate(" + @scaleX(0) + ")")
setScale : ->
@scaleX = d3.scale.linear().domain([0, @data.length]).range([-5, @width])
@scaleY = d3.scale.linear().domain([_.max(@data), _.min(@data)]).range([0, @height])
pushData : (value)->
@data.push(value)
@setScale()
@redraw()
Sparkline.defaults =
transitionTime : 1000
ease : 'linear'
interpolate : 'basis'
window.Sparkline = Sparkline
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment