Published
Edited
Jun 7, 2020
1 fork
Importers
Insert cell
Insert cell
chart = {
var svg = d3.create("svg")
.attr("viewBox", [0, 0, dimensions.width, dimensions.height])
var g = svg
.append("g")
.attr("transform", "translate(" + dimensions.width / 2 + "," + dimensions.height / 2 + ")");
let total = 0;
for (const k in data) {
total += data[k]
}
var color = d3.scaleOrdinal()
.domain(Object.keys(data))
.range(d3.schemeDark2);
var pie = d3.pie()
.sort(null) // Do not sort group by size
.value(function(d) {return d.value; })
var data_ready = pie(d3.entries(data))
var arc = d3.arc()
.innerRadius(radius * 0.6) // This is the size of the donut hole
.outerRadius(radius * 0.9)


g
.selectAll('allSlices')
.data(data_ready)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d){ return(color(d.data.key)) })
.attr("stroke", "white")
.style("stroke-width", "2px")
.style("opacity", 1)
.on('mouseenter', function(d) {
g.selectAll('path').filter(p => p.data.key !== d.data.key).style('opacity', 0.2);
g.append('text')
.datum(d)
.style('font-size', width/ 20)
.style('fill', '#888')
.attr('data-id', d => d.data.key)
.attr('text-anchor', 'middle')
.attr('y', -0.12*radius + width/40)
.text(d => d3.format(',')(d.data.value) + ' words ('+d3.format('.1%')(d.data.value/total)+')')
.attr('opacity',1);
g.append('text')
.datum(d)
.style('font-size', width/ 20)
.style('fill', '#888')
.attr('data-id', d => d.data.key)
.attr('text-anchor', 'middle')
.attr('y', width/40)
.text(d => `from ${d.data.key}`)
.attr('opacity',1);
g.append('text')
.datum(d)
.style('font-size', width/ 20)
.style('fill', '#888')
.attr('data-id', d => d.data.key)
.attr('text-anchor', 'middle')
.attr('y', 0.12*radius + width/40)
.text(d => `POVs`)
.attr('opacity',1);
})
.on('mouseout', function(d) {
g.selectAll(`text[data-id="${d.data.key}"]`).remove();
g.selectAll('path').style('opacity', 1);
})
return svg.node()
}
Insert cell
data = ({ Female: 21697, Male: 288240, Unknown:254})
Insert cell
radius = Math.min(width, dimensions.height) / 2 - dimensions.margin.left
Insert cell
import {hex} from "@luciyer/hexgen"
Insert cell
dimensions = ({
height:width,
width: width,
margin: {
top: 10,
right: 10,
bottom: 10,
left: 10,
}
})
Insert cell
d3 = require("d3@5")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more