Skip to content

Instantly share code, notes, and snippets.

@1Cr18Ni9
Last active January 10, 2017 13:08
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 1Cr18Ni9/f80c30dc9af22c635190066968b7d396 to your computer and use it in GitHub Desktop.
Save 1Cr18Ni9/f80c30dc9af22c635190066968b7d396 to your computer and use it in GitHub Desktop.
Pie Chart II
license: mit

Built with blockbuilder.org

This example is animated with attrTween, if you hover pie partions you will get it.

At the begining, I got two mistakes:

  • Chained outerRadius attribute with arc generator, which make arc generator with a fixed outerRadius;

  • Constructing path works fine, but I forget every path tag doesn't bind the outerRadius data. After posting help on stackflow, I get the answer.

The code is enlighted by Mike Bostock's Extending Arcs.

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var Width = 500, Height = 400,
innerRadius = 45, outerRadius = 120;
var colors = d3.scale.ordinal()
.range(["#7b6888", "#6b486b",
"#a05d56", "#d0743c",
"#ff8c00", "#98abc5", "#8a89a6",]);
var svg = d3.select('body')
.append('svg')
.attr({ width: Width, height: Height });
var data = [40, 32, 35, 64, 83],
sum = d3.sum(data),
percent = d3.format('.1%');
var pieData = d3.layout.pie()
.sort(d3.ascending)(data);
var ArcGen = d3.svg.arc()
.innerRadius(innerRadius)
// define the outerRadius on path construction
.padAngle(0.02)
.startAngle(function(d){
return d.startAngle;
})
.endAngle(function(d){
return d.endAngle;
});
var group = svg.append('g')
.attr('transform', 'translate(' + [Width / 2.0, Height / 2.0] + ')');
var segment = group.selectAll('g')
.data(pieData)
.enter()
.append('g')
.attr('transform', 'translate(0,0)');
segment
.append('path')
.each(function(d) { d.outerRadius = outerRadius; })
.attr('d', ArcGen)
.attr('class', 'piepath')
.attr('fill', function(d,i){ return colors(i); })
.on('mouseover', arcTween(outerRadius * 1.2, 0))
.on('mouseout', arcTween(outerRadius, 150));
segment
.append('text')
.text(function(d,i){ return percent(d.value / sum);})
.attr('text-anchor', 'middle')
.attr('transform', function(d){
return "translate(" + ArcGen.centroid(d) + ')' +
'rotate(' + ((d.startAngle + d.endAngle) / 2) * 180 / Math.PI + ')';
});
// event function
function arcTween(oRadius, delay){
return function(){
d3.select(this)
.transition()
.delay(delay)
.attrTween('d', function(d){
var i = d3.interpolate(d.outerRadius, oRadius);
return function(t){
d.outerRadius = i(t);
return ArcGen(d);
}
})
};
};
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment