Skip to content

Instantly share code, notes, and snippets.

@ivanvanderbyl
Created December 13, 2015 05:58
Show Gist options
  • Save ivanvanderbyl/3d3723925fdd58daff52 to your computer and use it in GitHub Desktop.
Save ivanvanderbyl/3d3723925fdd58daff52 to your computer and use it in GitHub Desktop.
A simple line chart using D3 Shape
import Ember from 'ember';
import DimensionsMixin from '../../mixins/dimensions';
import { line, catmullRom } from "d3-shape";
import { extent } from "d3-arrays";
import { time, linear } from "d3-scales";
const { computed, observer } = Ember;
export default Ember.Component.extend(DimensionsMixin, {
/**
* Our dataset. Represented as array of tuples.
*
* [
* [TIMESTAMP, VALUE],
* [TIMESTAMP, VALUE],
* ]
*
* @type {Array}
*/
values: [],
valuesDidChange: observer('values.[]', function(){
this.scheduleRedraw();
}),
xDomain: computed('values.[]', function() {
const values = this.get('values');
return extent(values, (d) => new Date(d[0]));
}),
yDomain: computed('values.[]', function() {
const values = this.get('values');
return extent(values, (d) => d[1]);
}),
xRange: computed('plotWidth', function() {
return [0, this.get('plotWidth')];
}),
yRange: computed('plotHeight', function() {
return [this.get('plotHeight'), 0];
}),
xScale: computed('xRange', 'xDomain', function() {
const { xRange, xDomain } = this.getProperties('xRange', 'xDomain');
return time().domain(xDomain).range(xRange);
}),
yScale: computed('yRange', 'yDomain', function() {
const { yRange, yDomain } = this.getProperties('yRange', 'yDomain');
return linear().domain(yDomain).range(yRange);
}),
lineFn: computed('xScale', 'yScale', function() {
const { xScale, yScale } = this.getProperties('xScale', 'yScale');
return line()
.x(function(d) { return xScale(d[0]); })
.y(function(d) { return yScale(d[1]); })
.curve(catmullRom);
}),
redraw() {
this.drawLines();
},
drawLines() {
const lineFn = this.get('lineFn');
const values = this.get('values');
const temperatureGroup = this.chart.select('g.lines');
const joinGroup = temperatureGroup.selectAll('path').data(values);
joinGroup.enter().append('path')
.attr('stroke', '#15CD72')
.attr('stroke-width', 2)
.attr('fill', 'none')
.attr('d', lineFn);
joinGroup.exit().remove();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment