Last active
August 29, 2015 13:57
-
-
Save blakedietz/9495248 to your computer and use it in GitHub Desktop.
Types of D3 Step Line Generation
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
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<html> | |
<head> | |
<title></title> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
function drawLine (interpolationType) | |
{ | |
var width = 200; | |
var height = 200; | |
var margin = {top : 0, right : 20, bottom : 0, left : 20}; | |
var svg = d3.select("body").append("svg") | |
.attr("width",width) | |
.attr("height",height); | |
var data = | |
[ | |
{ x:1 , y:1}, | |
{ x:2 , y:2}, | |
{ x:3 , y:1}, | |
{ x:4 , y:2}, | |
{ x:5 , y:1}, | |
{ x:6 , y:1}, | |
{ x:7 , y:2}, | |
{ x:8 , y:2}, | |
]; | |
var xDomain = d3.extent(data.map(function(datum){return datum.x;})); | |
xDomain[0] = xDomain[0] * .2 - xDomain[0]; | |
xDomain[1] = xDomain[1] * .2 + xDomain[1]; | |
var yDomain = d3.extent(data.map(function(datum){return datum.y;})); | |
yDomain[0] = yDomain[0] * .2 - yDomain[0]; | |
yDomain[1] = yDomain[1] * .2 + yDomain[1]; | |
var xScale = d3.scale.linear().domain(xDomain).range([margin.right,width - margin.left]); | |
var yScale = d3.scale.linear().domain(yDomain).range([height,0]); | |
var lineGenerator = d3.svg.line() | |
.x(function(datum){return xScale(datum.x);}) | |
.y(function(datum){return yScale(datum.y);}) | |
.interpolate(interpolationType); | |
svg.append("path") | |
.attr("d",lineGenerator(data)) | |
.attr("fill","none") | |
.attr("stroke","black") | |
.attr("shape-rendering","crispEdges"); | |
svg.selectAll("circle") | |
.data(data).enter() | |
.append("circle") | |
.attr("cx", function(datum){ return xScale(datum.x)}) | |
.attr("cy", function(datum){ return yScale(datum.y)}) | |
.attr("r", 3) | |
.attr("fill", "black"); | |
svg.append("text") | |
.attr("x", 20) | |
.attr("y", 20) | |
.text(interpolationType); | |
} | |
var step = drawLine("step"); | |
var stepAfter = drawLine("step-after"); | |
var stepBefore = drawLine("step-before"); | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment