Skip to content

Instantly share code, notes, and snippets.

@farazshuja
Last active July 22, 2016 06:27
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 farazshuja/e2cb52828c080ba85da5458e2304a61f to your computer and use it in GitHub Desktop.
Save farazshuja/e2cb52828c080ba85da5458e2304a61f to your computer and use it in GitHub Desktop.
D3 Pie chart with percentage outside
license: gpl-3.0
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; text-align: center; }
</style>
</head>
<body>
<script>
var data = [
{name: 'cats', count: 3, percentage: 2, color: '#000000'},
{name: 'dogs', count: 10, percentage: 8, color: '#f8b70a'},
{name: 'horses', count: 17, percentage: 15, color: '#6149c6'},
{name: 'goats', count: 47, percentage: 41, color: '#9f8170'},
{name: 'cows', count: 35, percentage: 31, color: '#8ABD4A'},
];
var width = 540,
height = 540,
radius = 200;
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.pie()
.sort(null)
.value(function(d) {
return d.count;
});
var svg = d3.select('body').append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g");
g.append("path")
.attr("d", arc)
.style("fill", function(d,i) {
return d.data.color;
});
g.append("text")
.attr("transform", function(d) {
var _d = arc.centroid(d);
_d[0] *= 2.2; //multiply by a constant factor
_d[1] *= 2.2; //multiply by a constant factor
return "translate(" + _d + ")";
})
.attr("dy", ".50em")
.style("text-anchor", "middle")
.text(function(d) {
if(d.data.percentage < 8) {
return '';
}
return d.data.percentage + '%';
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment