Skip to content

Instantly share code, notes, and snippets.

@m99coder
Last active August 29, 2015 14:24
Show Gist options
  • Save m99coder/1fdb1ec3d80fe36466fe to your computer and use it in GitHub Desktop.
Save m99coder/1fdb1ec3d80fe36466fe to your computer and use it in GitHub Desktop.
// data
var data = [
{timestamp: 1, value: 7},
{timestamp: 2, value: 8},
{timestamp: 3, value: 12},
{timestamp: 4, value: 16},
{timestamp: 5, value: 21},
{timestamp: 6, value: 22},
{timestamp: 7, value: 13},
{timestamp: 8, value: 8},
{timestamp: 9, value: 2}
];
// define chart
d3.chart('LineChart', {
initialize: function(opts) {
var chart = this;
// inner padding
var PADDING = 10;
// background
chart.base.append('rect')
.classed('background', true)
.attr('x', 0)
.attr('y', 0)
.attr('width', opts.width)
.attr('height', opts.height);
// clipping path
chart.base.append('clipPath')
.attr('id', 'chart-area')
.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', opts.width)
.attr('height', opts.height);
var path =
chart.base.append('path')
.classed('line', true)
.attr('clip-path', 'url(#chart-area)');
chart.x = d3.time.scale().range([PADDING, opts.width - PADDING]);
chart.y = d3.scale.linear().range([opts.height - PADDING, PADDING]);
var line =
d3.svg.line()
.x(function(d) {
return chart.x(d.timestamp);
})
.y(function(d) {
return chart.y(d.value);
});
chart.base.attr('height', opts.height);
chart.base.attr('width', opts.width);
// line
chart.layer('line', path, {
insert: function() {
return this;
},
dataBind: function(data) {
return this.data([data]).attr('d', line);
}
});
// circles
chart.layer('circles', this.base.append('g'), {
insert: function() {
return this.append('circle')
.classed('point', true)
.attr('cx', function(d, i) {
return chart.x(d.timestamp);
})
.attr('cy', function(d, i) {
return chart.y(d.value);
})
.attr('r', 5);
},
dataBind: function(data) {
return this.selectAll('circle')
.data(data)
.attr('cx', function(d, i) {
return chart.x(d.timestamp);
})
.attr('cy', function(d, i) {
return chart.y(d.value);
});
}
});
},
transform: function(data) {
this.x.domain(d3.extent(data, function(d) {
return d.timestamp;
}));
this.y.domain(d3.extent(data, function(d) {
return d.value;
}));
return data;
}
});
d3.select(element[0])
.append('svg')
.chart('LineChart', {
width: 600,
height: 160
})
.draw(data);
// update
window.setTimeout(function() {
data.push({timestamp: 10, value: 1});
data[5].value = 35;
}, 3000);
window.setTimeout(function() {
delete data[0];
}, 6000);
@m99coder
Copy link
Author

In this version the circles update. I wonder if I really need the duplicated code in insert and dataBind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment