Skip to content

Instantly share code, notes, and snippets.

@HectorLS
Last active December 14, 2015 12:30
Show Gist options
  • Save HectorLS/8334d3b70999c5d17c85 to your computer and use it in GitHub Desktop.
Save HectorLS/8334d3b70999c5d17c85 to your computer and use it in GitHub Desktop.
Update Pattern -- Bars
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:20px;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width: 100%; height: 100%; }
.chart rect {
fill: steelblue;
stroke: red;
}
svg {
border: 2px solid black;
}
</style>
</head>
<body>
<script>
// Random values
var t = 1297110663, // start time (seconds since epoch)
v = 70, // start value (subscribers)
data = d3.range(33).map(next); // starting dataset
function next() {
return {
time: ++t,
value: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5)))
};
}
setInterval(function() {
data.shift();
data.push(next());
updateData();
}, 1500);
// ================================== //
// Chart Size
var margin = {top: 20, right: 10, bottom: 20, left: 10},
svgWidth = 20,
svgHeight = 80,
contentWidth = svgWidth - margin.left - margin.right,
contentHeight = svgHeight - margin.top - margin.bottom;
var svg = d3.select("body")
.append("svg")
.attr("class", "chart")
.attr("width", svgWidth * data.length - 1)
.attr("height", svgHeight)
.append("g")
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');
// Scales
var xScale = d3.scale.linear()
.domain([0, 1])
.range([0, svgWidth]);
var yScale = d3.scale.linear()
.domain([0, 100])
.rangeRound([0, svgHeight]);
svg.append("line")
.attr("x1", 0)
.attr("x2", svgWidth * data.length)
.attr("y1", svgHeight - .5)
.attr("y2", svgHeight - .5)
.attr("stroke", "#000");
// Initial Display
updateData();
function updateData() {
// Data Join
var rect = svg.selectAll("rect")
.data(data, function(d) { return d.time; });
// Enter…
// ¿¿ Append or insert ??
rect.enter().append("rect", "line")
.attr("x", function(d, i) { return xScale(i + 1) - .5; })
.attr("y", function(d) { return svgHeight - yScale(d.value) - .5; })
.attr("width", svgWidth)
.attr("height", function(d) { return yScale(d.value); })
.transition()
.duration(750)
.attr("x", function(d, i) { return xScale(i) - .5; });
// Update…
rect.transition()
.duration(750)
.attr("x", function(d, i) { return xScale(i) - .5; });
// Exit…
rect.exit().transition()
.duration(750)
.attr("x", function(d, i) { return xScale(i - 2) - .5; })
.remove();
}
// Base on:
// https://strongriley.github.io/d3/tutorial/bar-2.html
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment