Line Interpolation (Smoothing)
HTML
<script src="https://raw.github.com/mbostock/d3/master/d3.v2.min.js"></script>
<script src="http://d3js.org/d3.v2.js"></script>
Change interpolation:
<select id="interpolations" >
<option value="linear"> linear</option>
<option value="step-before"> step-before</option>
<option value="step-after"> step-after</option>
<option value="basis"> basis</option>
<option value="basis-open"> basis-open</option>
<option value="basis-closed"> basis-closed</option>
<option value="bundle"> bundle</option>
<option value="cardinal" selected> cardinal</option>
<option value="cardinal-open"> cardinal-open</option>
<option value="cardinal-closed">cardinal-closed</option>
<option value="monotone"> monotone</option>
</select>
<br>
CSS
svg {
border: thin black solid;
}
.dot {
fill: none;
stroke: black;
stroke-width: 4px;
stroke-dasharray: 8px;
}
.poly {
stroke: steelblue;
stroke-width: 10px;
}
input {
text-align: center;
}
JavaScript
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var points = [
[ 0, 100],
[50, 100],
[100, 100],
[150, 100],
[200, 170],
[250, 100],
[300, 100],
[350, 100],
];
//Draw underlying point coordinates for reference:
var circles = svg.selectAll("circle")
.data(points)
.enter()
.append("circle");
circles.attr("cx", function (d) { return d[0]; })
.attr("cy", function (d) { return d[1]; })
.attr("r", function (d) { return 20; })
.attr('class', 'dot');
//Draw the path (line):
var path = svg.append('path')
.data([points])
//.attr('d', d3.svg.line().interpolate('basis'))
.attr('stroke-weight', '5px')
.attr('fill', 'none')
.attr('class', 'poly');
//Change interpolation mode
var interpols = document.getElementById('interpolations');
function change() {
var method = interpols.options[interpols.selectedIndex].value;
path.transition().attr('d', d3.svg.line().interpolate(method));
}
interpols.onchange = change;
change();
/*
Interpolation Methods
For more about them head on over to the D3 wiki and look for 'line.interpolate'.
linear – Normal line (jagged).
step-before – stepping graph alternating between vert and horz segments.
step-after - stepping graph alternating between horz and vert segments.
basis - B-spline, with control point duplication on the ends (that's the one above).
basis-open - open B-spline; may not intersect start or end.
basis-closed - closed B-spline with start and the end closed in a loop.
bundle - equivalent to basis, except a separate tension parameter is used to straighten the spline
cardinal - a Cardinal spline, with control point duplication on the ends.
cardinal-open - open cardinal spline; may not intersect start or end, but will intersect other ctrl points
cardinal-closed - a closed Cardinal spline, looped back on itself.
monotone...