Skip to content

Instantly share code, notes, and snippets.

@vjwilson
Created April 7, 2019 21:58
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 vjwilson/8355ec964046e393c3dc9b040779dd2c to your computer and use it in GitHub Desktop.
Save vjwilson/8355ec964046e393c3dc9b040779dd2c to your computer and use it in GitHub Desktop.
pie chart browser usage
license: mit
<!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; }
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var width = svg.attr("width");
var height = svg.attr("height");
var radius = Math.min(width, height) / 2;
var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var data = [
{ browser: 'Chrome', percent: 73.70 },
{ browser: 'IE/Edge', percent: 4.90 },
{ browser: 'Firefox', percent: 15.40 },
{ browser: 'Safari', percent: 3.60 }
];
var color = d3.scaleOrdinal(['#4daf4a','#377eb8','#ff7f00','#984ea3','#e41a1c']);
// Generate the pie
var pie = d3.pie().value(function(d) {
return d.percent;
});
// Generate the arcs
var arc = d3.arc()
.innerRadius(0)
.outerRadius(radius - 50);
var label = d3.arc()
.outerRadius(radius)
.innerRadius(radius - 20);
//Generate groups
var arcs = g.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc")
//Draw arc paths
arcs.append("path")
.attr("fill", function(d) {
return color(d.data.browser);
})
.attr("d", arc);
arcs.append("text")
.attr("transform", function(d) {
return "translate(" + label.centroid(d) + ")";
})
.attr('text-anchor', 'middle')
.text(function(d) {
console.log('d', d);
return d.data.browser + ' (' + d.data.percent + '%)';
});
svg.append("g")
.attr("transform", "translate(" + (width / 2) + "," + (height - 20) + ")")
.append("text")
.text("Browser use statistics - Jan 2017")
.attr("class", "title")
.attr('text-anchor', 'middle');
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment