Last active
August 29, 2015 13:59
-
-
Save ruedap/10475534 to your computer and use it in GitHub Desktop.
D3 example: basic bar chart with frame border
This file contains hidden or 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)) | |
| .attr('fill', '#cadce5') | |
| el.selectAll('.data') | |
| .append('path') | |
| .attr('d', (d, i) -> rectBorderPath(d, i, h, xScale, yScale)) | |
| .attr('fill', 'none') | |
| .attr('stroke', '#9eb1cc') | |
| .attr('stroke-width', 3) | |
| rectBorderPath = (d, i, h, xScale, yScale) -> | |
| _x = xScale(i) | |
| _y = h - yScale(d) | |
| _w = xScale.rangeBand() | |
| _h = yScale(d) | |
| _data = [ [_x, h], [_x, _y], [_x + _w, _y], [_x + _w, h] ] | |
| d3.svg.line().x((d) -> d[0]).y((d) -> d[1])(_data) | |
| margin = top: 20, right: 10, bottom: 20, left: 10 | |
| new D3Example('body', '700', '394', margin).render() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
前述の書き方ではそもそも棒グラフとしての高さが変わってしまうからダメで、rect要素の内側に線を引くためにまずはpath要素で描画するようにしてみたのが以下。これをさらに改良してline要素で引こうとすると小数点の配置が必要になりそう。