Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active Jan 16, 2020
Embed
What would you like to do?
Polar Plot
license: gpl-3.0

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!

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.frame {
fill: none;
stroke: #000;
}
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis circle {
fill: none;
stroke: #777;
stroke-dasharray: 1,4;
}
.axis :last-of-type circle {
stroke: #333;
stroke-dasharray: none;
}
.line {
fill: none;
stroke: red;
stroke-width: 1.5px;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var data = d3.range(0, 2 * Math.PI, .01).map(function(t) {
return [t, Math.sin(2 * t) * Math.cos(2 * t)];
});
var width = 960,
height = 500,
radius = Math.min(width, height) / 2 - 30;
var r = d3.scale.linear()
.domain([0, .5])
.range([0, radius]);
var line = d3.svg.line.radial()
.radius(function(d) { return r(d[1]); })
.angle(function(d) { return -d[0] + Math.PI / 2; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var gr = svg.append("g")
.attr("class", "r axis")
.selectAll("g")
.data(r.ticks(5).slice(1))
.enter().append("g");
gr.append("circle")
.attr("r", r);
gr.append("text")
.attr("y", function(d) { return -r(d) - 4; })
.attr("transform", "rotate(15)")
.style("text-anchor", "middle")
.text(function(d) { return d; });
var ga = svg.append("g")
.attr("class", "a axis")
.selectAll("g")
.data(d3.range(0, 360, 30))
.enter().append("g")
.attr("transform", function(d) { return "rotate(" + -d + ")"; });
ga.append("line")
.attr("x2", radius);
ga.append("text")
.attr("x", radius + 6)
.attr("dy", ".35em")
.style("text-anchor", function(d) { return d < 270 && d > 90 ? "end" : null; })
.attr("transform", function(d) { return d < 270 && d > 90 ? "rotate(180 " + (radius + 6) + ",0)" : null; })
.text(function(d) { return d + "°"; });
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment