How to append div to middle of pie piece in D3
I create a pie chart, for which I want to append div into the middle of pie piece that user is hovering over, for instance:
For now as you can see my div is being displayed in the mid point of an arc, and I want it to be displayed in center something like this blue rectangle. I feel like for this I need to find a mid point between a center of pie chart and center of arc.
Here is my code:
let width = 600
let height = 600
let margin = 20
let radius = Math.min(width, height) / 2 - margin;
const colors = ['#ffd384','#94ebcd','#fbaccc','#1a78be','#fa7f72', '#5033ec']
var svg = d3.select(".canvas")
.append("svg")
.style('display', 'block')
.style('overflow', 'visible')
.attr("viewBox", `0 0 ${width} ${height}`)
var g = svg.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var data = [
{continent: 'Africa', infected: 8790143},
{continent: 'Europe', infected: 215424950},
{continent: 'NAmerica', infected: 153251277},
{continent: 'SAmerica', infected: 54913452},
{continent: 'Asia', infected: 57882962},
{continent: "Oceania", infected: 21702163}
];
var ordScale = d3.scaleOrdinal()
.domain(data)
.range(colors);
var pie = d3.pie().value(function(d) {
return d.infected;
});
var arc = d3.arc()
.outerRadius(radius)
.innerRadius(0);
var outerArc = d3.arc()
.outerRadius(radius* 1)
.innerRadius(radius* 1);
g.selectAll("arc")
.data(pie(data))
.join(function (enter) {
enter.append("path")
.attr("d", arc)
.attr("fill", d => ordScale(d.data.continent))
.attr('id', d => `arc_${d.data.continent}`)
.style('transition', `all 250ms ease 0s`)
.on('mouseover', function (event, d){
selectArc(d3.select(this), g.selectAll('path'), ordScale(d.data))
// Code to append div to center of Pie piece
d3.select('.canvas').select('div').classed('hidden', false)
.style('left', `calc(50% + ${arc.centroid(d)[0]}px)`)
.style('top', `calc(50% + ${arc.centroid(d)[1]}px)`)
.style('transform', `translate(-50%, -50%)`)
})
.on('mouseout', function (event, d) {
d3.select(this).attr('transform', `scale(1)`)
d3.selectAll('path').attr('fill', d => ordScale(d.data)).attr('stroke', null)
d3.select('.canvas').select('div')
.classed('hidden', true)
},)
})
How many English words
do you know?
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
how many words do you know
Powered by Examplum