New Year's Resolution for 2017: Make a D3 Block a day to teach myself D3. This is Number 12. This example steps away from maps. It's a pie/donut chart with a couple of mouseover effects. HUGE struggle to figure out how to get the count into the hole of the donut (Thanks @bclinkinbeard). Also playing with some CSS (a separate file for this example) to see what's possible.
xxxxxxxxxx
<meta charset="utf-8">
<head>
<title>D3 Block-a-Day: Day 12, January 12, 2017</title>
<link rel="stylesheet" href="normalize.css">
</head>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<div id="chart"></div>
<script>
var dataset = [
{ label: 'Abulia', count: 10 },
{ label: 'Betelgeuse', count: 20 },
{ label: 'Cantaloupe', count: 30 },
{ label: 'Dijkstra', count: 40 }
];
var width = 960;
var height = 600;
var radius = Math.min(width, height) / 3;
var color = d3.scaleOrdinal(d3.schemeCategory20b);
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var svgContainer = d3.select("#chart")
.append("svg")
.attr("width", width)
.attr("height", height);
var arc = d3.arc()
.innerRadius(100)
.outerRadius(radius);
var pie = d3.pie()
.value(function(d) { return d.count; })
.sort(null);
var tooltip = d3.select('#chart')
.append('div')
.attr('class', 'hidden tooltip');
var centerLabel = svg
.append('text')
.attr('id', 'centerText')
.attr('class', 'label')
.attr('x', 0)
.attr('y', 30)
.attr('text-anchor', 'middle');
var donutChart = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d) {
return color(d.data.label);
})
.on('mousemove', function(d) {
var mouse = d3.mouse(svg.node()).map(function(d) {
return parseInt(d)
});
d3.select('#centerText').text(d.data.count);
tooltip.classed('hidden', false)
.attr('style', 'left:' + (mouse[0] + width/2) +'px; top:' + (mouse[1] + height/2) + 'px')
.html(d.data.label)
})
.on('mouseout', function() {
tooltip.classed('hidden', true);
d3.select('#centerText').text(null);
});
</script>
</body>
https://d3js.org/d3.v4.min.js