Built with blockbuilder.org
There is also this solution to the similar problem https://stackoverflow.com/questions/35639290/d3js-pie-chart-gradient
license: mit |
Built with blockbuilder.org
There is also this solution to the similar problem https://stackoverflow.com/questions/35639290/d3js-pie-chart-gradient
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<!DOCTYPE html> | |
<html> | |
<body> | |
<script> | |
let data = [25,30,40,17]; | |
let height = 750; | |
let width = height; | |
let radius = height * 0.4; | |
let hole = radius * 0.5; | |
let colour = d3.scaleSequential(d3.interpolatePlasma) | |
let svg = d3.select('body') | |
.append('svg') | |
.attr('width', width) | |
.attr('height', height) | |
let arcFill = svg.append('g') | |
.attr('transform', 'translate(' + width/2 + ',' + width/2 + ')'); | |
let arcOutline = svg.append('g') | |
.attr('transform', 'translate(' + width/2 + ',' + width/2 + ')'); | |
let arc = d3.arc() | |
.innerRadius(hole) | |
.outerRadius(radius); | |
let pie = d3.pie() | |
.sort(null) | |
.value(function(d) { return d; }) | |
data = pie(data); | |
arcOutline.selectAll('.arc') | |
.data(data) | |
.enter() | |
.append('path') | |
.attr('class', 'arc') | |
.attr('d', arc) | |
.style('fill', function(d){ | |
return createGradient(d) | |
}) | |
.style("stroke", "white") | |
.style("stroke-width", "3px") | |
function createGradient(d) { | |
let miniArcs = [] | |
let angleExtent = d.endAngle - d.startAngle | |
let noOfArcs = angleExtent * 75 //seems like a good number | |
colour.domain([0, noOfArcs]) | |
let miniArcAngle = angleExtent/noOfArcs | |
for (var j = 0; j < noOfArcs; j++) { | |
let miniArc = {} | |
miniArc.startAngle = d.startAngle + (miniArcAngle * j) | |
//0.01 so the colours overlap slightly, so there's no funny artefacts. | |
miniArc.endAngle = miniArc.startAngle + miniArcAngle + 0.01 | |
//unless it goes beyond the end of the parent arc | |
miniArc.endAngle = miniArc.endAngle > d.endAngle ? d.endAngle : miniArc.endAngle | |
miniArcs.push(miniArc) | |
} | |
arcFill.selectAll('.mini-arc') | |
.data(miniArcs) | |
.enter() | |
.append("g") | |
.append('path') | |
.attr('class', 'arc') | |
.attr('d', arc) | |
.style("fill", function(a, i){ return colour(i) }) | |
return "none" | |
} | |
</script> | |
</body> | |
</html> |