Skip to content

Instantly share code, notes, and snippets.

@abrahamdu
Last active August 3, 2017 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abrahamdu/2038544bffad6b5b25760b42ef519a7e to your computer and use it in GitHub Desktop.
Save abrahamdu/2038544bffad6b5b25760b42ef519a7e to your computer and use it in GitHub Desktop.
Pyramid Pie Chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body {
background-color: lightgrey;
}
svg {
width: 100%;
height: 100%;
position: center;
}
.slice:hover{
fill:red;
}
</style>
</head>
<body>
<svg width="960" height="500"></svg>
<script>
var margin = {top: 30, right: 30, bottom: 50, left: 30};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(["#0095D9", "#9C9536", "#F5E837"]);
var data = [
{"type":"Sky","pop":0.75},
{"type":"Shady side of pyramid","pop":0.07},
{"type":"Sunny side of pyramid","pop":0.18}
];
var g = d3.select("svg")
.append("g")
.attr("transform", "translate(" + width / 1.8 + "," + height / 1.6 + ")");
var pie = d3.pie().sort(null)
.value(function(d) { return d.pop; })(data);
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0)
.startAngle(function(d) { return d.startAngle + Math.PI*1.2; })
.endAngle(function(d) { return d.endAngle + Math.PI*1.2; });
var pyramid = g.selectAll(".arc")
.data(pie)
.enter()
.append("g")
.attr("class", "arc");
pyramid.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.type);});
var legend = g.append("g")
.attr("class", "legend")
.attr("font-family", "sans-serif")
.attr("font-size", 20)
.attr("text-anchor", "start")
.attr("transform", "translate(-40,100)")
.selectAll("g")
.data(pie)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(20," + i * 20 + ")"; });
legend.append("text")
.attr("x", radius + 10)
.attr("y", 9)
.attr("dy", "0.32em")
.text(function(d) { return d.data.type; });
legend.append("rect")
.attr("x", radius - 10)
.attr("width", 19)
.attr("height", 19)
.attr("fill", function(d) { return color(d.data.type);});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment