Created
April 11, 2014 12:50
-
-
Save ruedap/10466055 to your computer and use it in GitHub Desktop.
D3 example: basic bar chart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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