Last active
October 15, 2015 04:24
-
-
Save efekarakus/660b3c47dcdeb050a75b to your computer and use it in GitHub Desktop.
Binary Step Plot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Step Graph</title> | |
<style> | |
path.steps { | |
stroke: #000; | |
stroke-width: 3; | |
fill: none; | |
} | |
</style> | |
</head> | |
<body> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script> | |
<script src="./step.js" charset="utf-8"></script> | |
<script> | |
var data = [1,0,0,1,1,1,0,0,1,1,0,1,0,1,1,1,1,0,1,0,1,0,0,0]; | |
var chart = step() | |
.width(700) | |
.height(50) | |
.margin({top: 10, left: 5, right: 5, bottom: 10}); | |
d3.select("body") | |
.datum(data) | |
.call(chart); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var step = function() { | |
var margin = {top: 0, right: 0, bottom: 0, left: 0}, | |
width = 500, | |
height = 200; | |
function coordinates(data) { | |
var Δx = width / data.length; | |
var coords = []; | |
data.forEach(function(d, i) { | |
var start = d === 1 ? {x: i* Δx, y: 0} : {x: i*Δx, y: height}, | |
end = {x: start.x + Δx, y: start.y}; | |
coords.push(start); | |
coords.push(end); | |
}); | |
return coords; | |
} | |
function chart(selection) { | |
selection.each(function(data) { | |
var svg = d3.select(this).append("svg") | |
.attr("width", width + margin.left + margin.right) | |
.attr("height", height + margin.top + margin.bottom) | |
.append("g") | |
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")"); | |
var line = d3.svg.line() | |
.x(function(d) { return d.x; }) | |
.y(function(d) { return d.y; }) | |
.interpolate("linear"); | |
var coords = coordinates(data); | |
console.log(coords); | |
svg.append("path") | |
.attr("d", line(coords)) | |
.attr("class", "steps"); | |
}); | |
} | |
chart.margin = function(_) { | |
if (!arguments.length) return undefined; | |
margin = _; | |
return chart; | |
} | |
chart.width = function(_) { | |
if (!arguments.length) return undefined; | |
width = _; | |
return chart; | |
} | |
chart.height = function(_) { | |
if (!arguments.length) return undefined; | |
height = _; | |
return chart; | |
} | |
return chart; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment