Skip to content

Instantly share code, notes, and snippets.

@mattbaker
Last active December 16, 2015 08:49
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 mattbaker/3b9e10baf9dafb100d9e to your computer and use it in GitHub Desktop.
Save mattbaker/3b9e10baf9dafb100d9e to your computer and use it in GitHub Desktop.
Ex. 6 in Reactive Bar Chart Article
function BarChart(svg) {
var svg = d3.select(svg);
var barContainer = svg.append("g");
var labelContainer = svg.append("g");
this.width = $R.state(200);
this.height = $R.state(200);
this.data = $R.state([]);
var y = $R(BarChart.y, this)
.bindTo(this.height, this.data);
var x = $R(BarChart.x, this)
.bindTo(this.width, this.data);
var bars = $R(BarChart.bars, this)
.bindTo(barContainer, this.data, this.height, x, y);
var labels = $R(BarChart.labels, this)
.bindTo(labelContainer, this.data, x, y);
}
BarChart.y = function (height, data) {
return d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.value })])
.range([height, 0]);
}
BarChart.x = function (width, data) {
return d3.scale.ordinal()
.domain(d3.range(0, data.length))
.rangeRoundBands([0, width], .1);
}
BarChart.bars = function (barContainer, data, height, x, y) {
var bars = barContainer.selectAll(".bar").data(data);
bars.enter().append("rect")
.attr("class", "bar");
bars.attr("x", function(d, i) { return x(i); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });
bars.exit().remove()
}
BarChart.labels = function (labelContainer, data, x, y) {
var labels = labelContainer.selectAll(".label").data(data);
labels.enter().append("text")
.attr("class", "label");
labels.attr("x", function(d, i) { return x(i) + x.rangeBand() / 2 - 8; })
.text(function (d,i) { return d.name; })
.attr("y", function(d) { return y(d.value) + 10; })
labels.exit().remove()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment