peppermcknight peppermcknight - 3 months ago 26
TypeScript Question

D3 Pie Chart Label Data Not Working

I'm making a pie chart component in angular2 using d3, and I've become stuck when trying to add text to the chart. I can see the text inside the element explorer in the developer tools but it's not showing on the chart. I have a feeling that theres probably something really silly that I'm doing but can't figure out what it could be. My code is below.

showChart() {
let widthRatio = 4;
let heightRatio = 3;
let radius = Math.min(widthRatio, heightRatio) / 2;

let color = d3.scaleOrdinal(d3.schemeCategory20b);

let svg = d3.select('#' + this.chartId)
.append('svg')
.attr('width', '100%')
.attr('height', '100%')
.attr('viewBox', '0 0 ' + widthRatio + ' ' + heightRatio)
.append('g')
.attr('transform', 'translate(' + (widthRatio / 2) + ',' + (heightRatio / 2) + ')');

let arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);

let labelArc = d3.arc()
.innerRadius(radius - 40)
.outerRadius(radius - 40);

let pie = d3.pie()
.value((d) => { return d.count; })
.sort(undefined);

let g = svg.selectAll('.arc')
.data(pie(this.chartData))
.enter()
.append('g')
.attr('class', 'arc');

g.append('path')
.attr('d', arc)
.style('fill', (d) => { return color(d.data.label); });

g.append('text')
.attr('transform', (d) => { return 'translate(' + labelArc.centroid(d) + ')'; })
.attr('dy', '.35em')
.text((d) => { return 'test'; });
}


Thanks for any help in advance.

Answer

Worked out what was wrong with this. I was using widthRatio and heightRatio to control to aspect ratio of the chart on resizing, but that meant that the label text was getting co-ordinates of 3 and 4 which was causing it to not show. In my case to fix this I changed the code so that the width and height would be set by the width and height of the parent container, which in turn is controlled by a bootstrap grid.

let width = parseInt(d3.select('#' + this.parentContainerId).style('width'));
let height = parseInt(d3.select('#' + this.parentContainerId).style('height'));
Comments