Skip to content

Instantly share code, notes, and snippets.



Last active May 31, 2020
What would you like to do?
fresh block
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<script src=""></script>
<!-- Color scale -->
<script src=""></script>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; font-family: Helvectica, Arial, sans-serif;}
<div id="my_dataviz"></div>
// set the dimensions and margins of the graph
var width = 450
height = 450
margin = 40
// The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin.
var radius = Math.min(width, height) / 2 - margin
// append the svg object to the div called 'my_dataviz'
var svg ="#my_dataviz")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Create dummy data
//var data = {"Climate change": 2, "Acidification": 3, "Chemicals":4, "Nitrogen & phosphorus":4, "Freshwater":1, "Land conversion":4, "Biodiversity":1, "Air pollution":3, "Ozone":4}
var data = {"Huarerenga": 2, "Tai waikawa": 3, "Chemicals":4, "Nitrogen & phosphorus":4, "Freshwater":1, "Land conversion":4, "Biodiversity":1, "Air pollution":3, "Ozone":4}
// set the color scale
var color = d3.scaleOrdinal()
// Compute the position of each group on the pie:
var pie = d3.pie()
.value(d => 1)
var data_ready = pie(d3.entries(data))
// Now I know that group A goes from 0 degrees to x degrees and so on.
// shape helper to build arcs:
var arcGen = d3.arc()
// Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
.attr('d', arcGen)
.attr('fill', d => 'steelblue' )
.attr("stroke", "black")
.attr("d", (d, i) => arcGen.innerRadius(radius - ( * 6))(d, i))
.style("stroke-width", "1px")
.style("opacity", 0.7)
// Now add the annotation. Use the centroid method to get the best coordinates
.text(d =>
.attr("transform", d => "translate(" + arcGen.centroid(d) + ")")
.style("text-anchor", "middle")
.style("font-size", 17)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment