Created
April 27, 2014 12:21
-
-
Save bryanhanson/11344247 to your computer and use it in GitHub Desktop.
Drawing a line in d3.js starting from separate x & y arrays
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"> | |
<body> | |
<script src = "http://d3js.org/d3.v3.min.js"> </script> | |
<script> | |
// Draw a very simple line using d3 functions | |
// using simple arrays of x and y values. | |
// Alas, you must convert to a more complex form | |
// to use them! | |
var margin = {top: 20, right: 20, bottom: 20, left: 20}, | |
width = 600 - margin.left - margin.right, | |
height = 270 - margin.top - margin.bottom; | |
var xdata = d3.range(0, 20); | |
var ydata = [1, 4, 5, 9, 10, 14, 15, 15, 11, 10, 5, 5, 4, 8, 7, 5, 5, 5, 8, 10]; | |
// d3.js functions want x,y data in a not-so-intuitive structure | |
// Assemble the needed array structure (Thanks to FernofTheAndes on SO) | |
// The new structure is technically an array of objects. | |
// Each object has the structure {property: value} | |
// In this case, each object is one x, y pair | |
var xy = []; // start empty, add each element one at a time | |
for(var i = 0; i < xdata.length; i++ ) { | |
xy.push({x: xdata[i], y: ydata[i]}); | |
} | |
console.log("xy is:", xy); // shows the data structure | |
var xscl = d3.scale.linear() | |
.domain(d3.extent(xy, function(d) {return d.x;})) //use just the x part | |
.range([margin.left, width + margin.left]) | |
var yscl = d3.scale.linear() | |
.domain(d3.extent(xy, function(d) {return d.y;})) // use just the y part | |
.range([height + margin.top, margin.top]) | |
var slice = d3.svg.line() | |
.x(function(d) { return xscl(d.x);}) // apply the x scale to the x data | |
.y(function(d) { return yscl(d.y);}) // apply the y scale to the y data | |
console.log("slice(xy) is:", slice(xy)); // shows the exact pen moves | |
var svg = d3.select("body") | |
.append("svg") | |
svg.append('rect') // outline for reference | |
.attr({x: margin.left, y: margin.top, | |
width: width, | |
height: height, | |
stroke: 'black', | |
'stroke-width': 0.5, | |
fill:'white'}); | |
svg.append("path") | |
.attr("class", "line") | |
.attr("d", slice(xy)) // use the return value of slice(xy) as the data, 'd' | |
.style("fill", "none") | |
.style("stroke", "red") | |
.style("stroke-width", 2); | |
</script> | |
</body> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it was very helpful, thank you.