Create a gist now

Instantly share code, notes, and snippets.

@mbostock /.block
Last active Feb 16, 2017

What would you like to do?
Line Interpolation
license: gpl-3.0

D3 2.10 allows you to implement custom interpolators for d3.svg.line and d3.svg.area. This contrived example shows how to draw arcs between data points using SVG’s elliptical arc path segments.

var line = d3.svg.line()
    .interpolate(function(points) { return points.join("A 1,1 0 0 1 "); })
    .x(function(d) { return x(d.x); })
    .y(function(d) { return y(d.y); });
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
.dot {
fill: white;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var data = d3.range(20).map(function(i) {
return {x: i / 19, y: (Math.sin(i / 3) + 2) / 4};
});
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.interpolate(function(points) { return points.join("A 1,1 0 0 1 "); }) // custom interpolator
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
var svg = d3.select("body").append("svg")
.datum(data)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("path")
.attr("class", "line")
.attr("d", line);
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", line.x())
.attr("cy", line.y())
.attr("r", 3.5);
</script>

Hello Mike,

function(points) { return points.join("L")} seems to work for interpolation but when i pass "monotone" or "basis" in the argument, it is not rendering the interpolation, what do you think might be the reason, can you please let me know whats the custo interpolation function for "monotone":

//works
var area = d3.svg.area()
.x(function(d) {
...
})
.y0(height)
.y1(function(d, i) {
...
})
.interpolate(function(points) { return points.join("L")});
//works
var area = d3.svg.area()
.x(function(d) {
...
})
.y0(height)
.y1(function(d, i) {
...
});
//doesnt apple the interpolation
var area = d3.svg.area()
.x(function(d) {
...
})
.y0(height)
.y1(function(d, i) {
...
})
.interpolate("monotone");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment