Paths in D3
4 May 2018
Today, let’s explore D3’s ability to draw paths.
<svg id="canvas" width="400" height="300" style="background-color:lightgray;"></svg>
Let’s add a simple path to our canvas. We will start with some simple (x, y)
coordinates. Remember that the point (0, 0)
is the top left corner. Our math minds tell us that (0, 0)
should be the bottom left corner, but our minds are wrong.
// Select the canvas object.
var svg = d3.select("#canvas");
// How do we define a line? Take a row of data. The x coordinate is the first element
// of the array; the y coordinate is the second element of the array.
var line = d3
.line()
.x(d => d[0])
.y(d => d[1]);
// Create a function to generate a random data set. To get a "pretty" graph, let's
// add the bottom left (0, height) and bottom right (width, height) corners to the
// graphic.
function generateRandomData() {
var data = [
[0, height],
[0, height * Math.random()],
[100, height * Math.random()],
[200, height * Math.random()],
[300, height * Math.random()],
[400, height * Math.random()],
[400, height]
];
console.log("generated data:", data);
return data;
}
// Assign the random data set.
var data = generateRandomData();
// Append new path to the SVG canvas.
var path = svg
.append("path")
.attr("fill", "lightblue")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line(data));
Pretty cool, huh? Now we should be able to generate any line chart.
Like all things in D3, we can apply transitions to paths. This transition will be applied whenever we click on the SVG canvas.
svg.on("click", function() {
// Generate a new data set and update the "d" attribute of the path.
var data = generateRandomData();
path.transition().attr("d", line(data));
});
This is some good stuff. Now go forth and manipulate data!