Skip to content

Instantly share code, notes, and snippets.

@ericsoco
Last active December 18, 2015 17:30
Show Gist options
  • Save ericsoco/ded6c0dc1383c60a5872 to your computer and use it in GitHub Desktop.
Save ericsoco/ded6c0dc1383c60a5872 to your computer and use it in GitHub Desktop.
Polar Plot

This example demonstrates the construction of a polar plot of a parametric function, sin(2t)cos(2t). A d3.svg.line.radial is used to draw the red line. Note the definition of the line’s angle: D3’s radial lines and areas proceed clockwise starting at 12 o’clock, while this plot proceeds counterclockwise starting at 3 o’clock!

forked from mbostock's block: Polar Plot

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.line {
fill: red;
fill-opacity: 0.5;
stroke: none;
}
#graph-container {
transform: rotateX(30deg);
}
</style>
<body>
<div id='graph-container'></div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var ARROW_SHAPE = [
{ x: 0.0, y: 0.0 },
{ x: 0.75, y: -0.01 },
{ x: 1.0, y: 0 },
{ x: 0.75, y: 0.01 },
{ x: 0.0, y: 0.0 }
];
var numArrows = 11;
var data = [];
for (var i=0; i<numArrows; i++) {
var offset = 0.25 + i/(2*(numArrows-1));
data.push(ARROW_SHAPE.map(function (pt) {
return {
x: pt.x,
y: offset + pt.y
};
}));
}
var arrowScale = 0;
var width = 960,
height = 800,
radius = Math.min(width, height) / 2 - 30;
var line = d3.svg.line.radial()
.radius(function(d) { return d.x * arrowScale * radius; })
.angle(function(d) { return 2*Math.PI - d.y * 2*Math.PI; })
.interpolate('cardinal');
var svg = d3.select("#graph-container").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + 0.1*height + ")");
svg.selectAll('path')
.data(data)
.enter().append('path')
.attr("class", "line")
.attr('d', line);
// animate in arrows
arrowScale = 1;
svg.selectAll('path').transition()
.duration(1000)
.delay(function (d, i) { return i * 100; })
.attr('d', line);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment