Skip to content

Instantly share code, notes, and snippets.

@fogonwater
Last active May 31, 2020 21:42
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 fogonwater/d47d7638af5634437ad561b6582fb393 to your computer and use it in GitHub Desktop.
Save fogonwater/d47d7638af5634437ad561b6582fb393 to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<!-- Color scale -->
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; font-family: Helvectica, Arial, sans-serif;}
</style>
</head>
<body>
<div id="my_dataviz"></div>
<script>
console.clear()
// 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 = d3.select("#my_dataviz")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.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()
.domain(data)
.range(d3.schemeSet2);
// 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()
.innerRadius(100)
.outerRadius(radius)
// Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('path')
.attr('d', arcGen)
.attr('fill', d => 'steelblue' )
.attr("stroke", "black")
.attr("d", (d, i) => arcGen.innerRadius(radius - (d.data.value * 6))(d, i))
.style("stroke-width", "1px")
.style("opacity", 0.7)
// Now add the annotation. Use the centroid method to get the best coordinates
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('text')
.text(d => d.data.key)
.attr("transform", d => "translate(" + arcGen.centroid(d) + ")")
.style("text-anchor", "middle")
.style("font-size", 17)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment