Skip to content

Instantly share code, notes, and snippets.

@plmrry
Last active August 29, 2015 14:27
Show Gist options
  • Save plmrry/1669d52e2dd8886dc7cb to your computer and use it in GitHub Desktop.
Save plmrry/1669d52e2dd8886dc7cb to your computer and use it in GitHub Desktop.
Bar Chart Update Pattern
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<meta charset="utf-8">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
var margin = { top: 10, left: 10, bottom: 10, right: 10 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var main = d3.select("body").append("svg")
.style({
width: width + margin.left + margin.right,
height: height + margin.top + margin.bottom
})
.append("g")
.attr({
transform: "translate(" + [margin.left, margin.top] + ")"
});
main.append("rect").attr({
width: width, height: height, fill: "none"
});
var dataA = [
{ name: "Joffrey", foo: 24, bar: 12 },
{ name: "Tyrion", foo: 54, bar: 45 },
{ name: "Arya", foo: 16, bar: 53 },
{ name: "Cersei", foo: 78, bar: 34 }
];
var dataB = [
{ name: "Tyrion", foo: 54, bar: 45 },
{ name: "Cersei", foo: 78, bar: 34 },
{ name: "Arya", foo: 45, bar: 53 },
{ name: "Joffrey", foo: 24, bar: 12 },
{ name: "Jon", foo: 92, bar: 18 }
];
var data = dataA;
window.setInterval(function() {
data = data == dataA ? dataB : dataA;
update();
}, 1000);
var x = d3.scale.ordinal()
.rangeBands([0, width], 0.1, 1);
var y = d3.scale.linear()
.domain([0, 100])
.range([height, 0]);
var color = d3.scale.category10();
update();
function update() {
x.domain(data.map(function(d) { return d.name; }));
var bar = main.selectAll(".bar").data(data, function(d) { return d.name; });
bar.enter().append("rect").classed("bar", true)
.attr({
width: x.rangeBand(),
height: 0,
x: function(d, i) { return x(d.name); },
y: y(0)
})
.style({
"fill-opacity": 0.5,
"fill": function(d, i) { return color(d.name); }
});
bar
.transition()
.attr({
width: x.rangeBand(),
height: function(d) { return height - y(d.foo); },
x: function(d, i) { return x(d.name); },
y: function(d, i) { return y(d.foo); }
});
bar.exit()
.transition()
.attr({
y: y(0),
height: 0
}).remove();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment