Skip to content

Instantly share code, notes, and snippets.

@ruedap
Created April 11, 2014 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruedap/10466055 to your computer and use it in GitHub Desktop.
Save ruedap/10466055 to your computer and use it in GitHub Desktop.
D3 example: basic bar chart
class D3Example
constructor: (@selector, width, height, @margin) ->
@el = @defineRootElement(@selector, +width, +height, @margin)
defineRootElement: (selector, width, height, margin) =>
@width = width - margin.left - margin.right
@height = height - margin.top - margin.bottom
d3.select(selector)
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', "translate(#{margin.left},#{margin.top})")
.attr('class', 'margin-convention-element')
render: (el = @el, w = @width, h = @height, margin = @margin) =>
data = [100, 50, 40, 20, 130]
xScale = d3.scale.ordinal().domain(d3.range(data.length))
xScale.rangeRoundBands([0, w], 0.1)
yScale = d3.scale.linear().domain([0, d3.max(data)])
yScale.range([0, h])
el.selectAll('g')
.data(data)
.enter()
.append('g')
.attr('class', 'data')
.append('rect')
.attr('x', (d, i) -> xScale(i))
.attr('width', xScale.rangeBand())
.attr('y', (d) -> h - yScale(d))
.attr('height', (d) -> yScale(d))
margin = top: 10, right: 10, bottom: 10, left: 10
new D3Example('body', '700', '394', margin).render()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment