Using D3 version 3, I'm trying to get text (in this case names from the json) to appear in the centre of the circles in a bubble chart.
I followed various tutorials. In the Chrome Developer Tools Elements window my text elements are visible as children of the SVG circle but are still not visible on screen.
I've put together an example on Codepen.
https://codepen.io/_d_v_/pen/MQyONV
const json = { companyA: 500, companyB: 200, companyC: 150, companyD: 100, companyE: 50 };
const colors = [ '#FF0000', '#03900F', '#0000FF', '#FF00FF', '#00FF00' ];
const diameter = 400;
const processData = data => {
const obj = data;
const newDataSet = [];
for(let prop in obj) {
newDataSet.push({name: prop, size: obj[prop]});
}
return {children: newDataSet};
}
const svg = d3.select('#graph').append('svg')
.attr('width', diameter)
.attr('height', diameter);
const bubble = d3.layout.pack()
.size([diameter, diameter])
.value( d => d.size )
.padding(30);
// generate data with calculated layout values
const nodes = bubble.nodes(processData(json)).filter(function(d) { return !d.children; }); // filter out the outer bubble
const vis = svg.selectAll('circle').data(nodes);
vis.enter().append('circle')
.attr('transform', d => 'translate(' + d.x + ',' + d.y + ')')
.attr('r', d => d.r)
.attr('fill', (d, i) => `${colors[i]}`);
vis.append('text')
.attr('dx', d => -20)
.attr('text-anchor', 'middle')
.attr('font-size', d => d.r / ((d.r * 10) / 100))
.attr('dy', d => d.r / ((d.r * 25) / 100))
.text(d => d.name)
Please can anyone show me where I'm going wrong? I just want text to appear in the centre of the SVG circle.
Many thanks in advance