Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active February 19, 2019 19:39
Embed
What would you like to do?
Arc generator (centroid)
license: gpl-3.0
height: 230
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Arc generator (centroid)</title>
</head>
<style>
text {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
fill: white;
text-anchor: middle;
}
path {
fill: orange;
stroke: white;
}
</style>
<body>
<svg width="700" height="220">
<g transform="translate(300, 110)"></g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
// Create an arc generator with configuration
var arcGenerator = d3.arc()
.innerRadius(20)
.outerRadius(100);
var arcData = [
{label: 'A', startAngle: 0, endAngle: 0.2},
{label: 'B', startAngle: 0.2, endAngle: 0.6},
{label: 'C', startAngle: 0.6, endAngle: 1.4},
{label: 'D', startAngle: 1.4, endAngle: 3},
{label: 'E', startAngle: 3, endAngle: 2* Math.PI}
];
// Create a path element and set its d attribute
d3.select('g')
.selectAll('path')
.data(arcData)
.enter()
.append('path')
.attr('d', arcGenerator);
// Add labels, using .centroid() to position
d3.select('g')
.selectAll('text')
.data(arcData)
.enter()
.append('text')
.each(function(d) {
var centroid = arcGenerator.centroid(d);
d3.select(this)
.attr('x', centroid[0])
.attr('y', centroid[1])
.attr('dy', '0.33em')
.text(d.label);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment