Skip to content

Instantly share code, notes, and snippets.

@Thanaporn-sk
Created August 2, 2017 14:22
Show Gist options
  • Save Thanaporn-sk/535737caf2824726fdbc68f88ff6430d to your computer and use it in GitHub Desktop.
Save Thanaporn-sk/535737caf2824726fdbc68f88ff6430d to your computer and use it in GitHub Desktop.
Pie Chart with Image Pattern
license: mit

Using SVG patterns to create pie charts with image fills. It dynamically calculates the spacing for the pattern to allow for space between each pie chart (some work still needs to be done to perfect these calculations). Ideally we want to be able to give it the width/height of each, the initial x/y and the vertical/horizontal padding between each.

forked from tlfrd's block: Pie Chart with Image Pattern

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.coin {
stroke: black;
}
.pie-segment {
stroke: black;
fill: white;
}
</style>
</head>
<body>
<script>
var width = 960,
height = 500;
var imageURL = "https://www.thenewpoundcoin.com/images/layout/pound-coin.png";
var circleSize = { width: 75, height: 75 },
circlePos = {
x: circleSize.width * 1,
y: circleSize.height * 3
};
var spacing = 30;
var angles = [0.1, 0.37, 0.2, 0.25, 0.1, 0.05, ];
var path = d3.arc()
.outerRadius(circleSize.width / 2)
.innerRadius(0)
.startAngle(0);
var generateArc = function(fraction) {
return path({endAngle: Math.PI * 2 * fraction})
}
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
svg.append("defs")
.append("pattern")
.attr("id", "money")
.attr('patternUnits', 'userSpaceOnUse')
.attr("width", circleSize.width + spacing)
.attr("height", circleSize.height)
.attr("x", circlePos.x - (circleSize.width / 2) + (spacing / 2))
.attr("y", circleSize.height / 2)
.append("image")
.attr("xlink:href", imageURL)
.attr("width", circleSize.width + spacing)
.attr("height", circleSize.height);
var cirlces = svg.selectAll("circle")
.data(angles)
.enter().append("circle")
.attr("class", "coin")
.attr("cx", function(d, i) { return (circlePos.x + spacing) * (i + 1) })
.attr("cy", circlePos.y)
.attr("r", circleSize.width / 2)
.attr("fill", "url(#money)");
var arcs = svg.selectAll("g")
.data(angles)
.enter().append("g")
.attr("transform", function(d, i) {
return "translate(" + (circlePos.x + spacing) * (i + 1) + ", " + circlePos.y + ")";
})
.append("path")
.attr("class", "pie-segment")
.attr("d", function(d) {
this._current = 0.0001;
return generateArc(this._current);
});
arcs
.data(angles)
.transition()
.duration(1000)
.attrTween("d", arcTween);
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return generateArc(i(t));
};
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment