Created
May 23, 2014 15:58
-
-
Save vierarb/9b1986a78d14f5dae60d to your computer and use it in GitHub Desktop.
Polar Area chart with d3js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var width = 750; | |
var height = 500; | |
var radius = 200; | |
var strokeColor = "#999"; | |
var strokeOpacity = 0.75; | |
var labelMargin = radius + 20; | |
var concentric = []; | |
for(var i = 1; i <= 10; i++) { | |
concentric.push((radius * i) / 10); | |
} | |
var data = [ | |
{ label: "1 Sector", color: "#113F8C", percentage: 100 }, | |
{ label: "2 Sector", color: "#01A4A4", percentage: 90 }, | |
{ label: "3 Sector", color: "#00A1CB", percentage: 70 }, | |
{ label: "4 Sector", color: "#61AE24", percentage: 90 }, | |
{ label: "5 Sector", color: "#D0D102", percentage: 55 }, | |
{ label: "6 Sector", color: "#D70060", percentage: 75 }, | |
{ label: "7 Sector", color: "#E54028", percentage: 85 }, | |
{ label: "8 Sector", color: "#F18D05", percentage: 100 } | |
]; | |
var arc = d3.svg.arc() | |
.innerRadius(0) | |
.outerRadius(function(d) { return (radius * d.data.percentage) / 100 }); | |
var pie = d3.layout.pie() | |
.value(function(d) { return 100 / data.length }) | |
var svg = d3.select("body") | |
.append("svg:svg") | |
.data([data]) | |
.attr("width", width) | |
.attr("height", height) | |
.append("svg:g") | |
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); | |
// Concentric cirlces | |
var concentric = svg.selectAll("g.concentric") | |
.data(concentric) | |
.enter() | |
.append("svg:g") | |
.attr("class", "concentric") | |
.style("opacity", strokeOpacity); | |
concentric.append("svg:circle") | |
.attr("r", function (d) { return d; }) | |
.style("stroke", strokeColor) | |
.style("fill", "none"); | |
// Slices | |
var g = svg.selectAll(".arc") | |
.data(pie(data)) | |
.enter() | |
.append("g") | |
.attr("class", "arc"); | |
g.append("path") | |
.attr("fill", function(d) { return d.data.color; }) | |
.attr("d", arc) | |
.style("stroke", "#fff") | |
.style("stroke-width", "1.5") | |
.style("opacity", 0.80) | |
// Text | |
g.append("svg:text") | |
.attr("transform", function(d) { | |
var coordinates = arc.centroid(d); | |
var a = coordinates[0]; | |
var b = coordinates[1]; | |
var h = Math.sqrt(a * a + b * b); | |
var translateX = (a / h * labelMargin); | |
var translateY = (b / h * labelMargin); | |
return "translate(" + translateX + ',' + translateY + ")"; | |
}) | |
.attr("dy", ".35em") | |
.attr("text-anchor", function(d) { | |
return (d.endAngle + d.startAngle) / 2 > Math.PI ? "end" : "start"; | |
}) | |
.text(function(d) { return d.data.label + " " + d.data.percentage + "%"; }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment