Cummings
Cummings

Reputation: 138

D3 V4 Pie Chart Angular2 Typescript path is incorrect

I have a working Angularjs D3v3 Pie Chart and have decided to port it to Angular5, and update it to D3 V4. I am getting the data, but the arcs are basically empty and I can't tell why.

Here is a snippet of my code:

export class PieChartComponent implements AfterViewInit {
@ViewChild("containerPieChart") element: ElementRef;

private host: D3.Selection<any>;
private svg: D3.Selection<any>;
private width: number;
private height: number;
private radius: number;
private htmlElement: HTMLElement;
private pieData: IData[];

constructor(private dataService: DataService) { }

ngAfterViewInit() {
    this.htmlElement = this.element.nativeElement;
    this.host = D3.select(this.htmlElement);
    this.dataService.$data.subscribe(data => {
        this.pieData = data;
        this.buildPie();
    });
}

private buildPie(): void {
    this.width = 400;
    this.height = 400;
    this.radius = Math.min(this.width, this.height) / 2;
    this.host.html("");
    let innerRadius = this.radius - 50;
    let outerRadius = this.radius - 10;

    this.svg = this.host.append("svg")
        .attr("viewBox", `0 0 ${this.width} ${this.height}`)
        .data([this.pieData])
        .attr('width', this.width)
        .attr('height', this.height)
        .append("g")
        .attr("transform", `translate(${this.width / 2},${this.height / 2})`);

    let pie = D3.pie().value((function(d) { return d})(this.pieData));
    let path = D3.arc().outerRadius( this.radius - 10).innerRadius(0);
    let label = D3.arc().outerRadius(this.radius - 40).innerRadius( this.radius - 40);

    let values = this.pieData.map(data => data.CASES);

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

    let pieColor = D3.scaleOrdinal(["Blue", "Teal", "Green", "Orange", "Purple", "Red", "Sienna"]); 

    arc.append('path')
        .attr('d', path)
        .attr('fill', function (d, i) {
            return pieColor(i);
        });

    arc.append("text")
        .attr("transform", (datum: any) => {
            datum.innerRadius = 0;
            datum.outerRadius = this.radius;
            return "translate(" + label.centroid(datum) + ")";
        })
        .text((datum, index) => this.pieData[index].CASES)
        .style("text-anchor", "middle");
}

I know there is something I am not seeing and any help would be appreciated. Full code is here:Pie Chart D3 V4

Upvotes: 1

Views: 1024

Answers (1)

Harpal
Harpal

Reputation: 12577

I think the error is when you are defining pie.

when I change this:

let pie = D3.pie().value((function(d) { return d})(this.pieData));

To this:

let pie = D3.pie().value((function(d) { return d}));

I get a pie chart back on your plunkr

Upvotes: 1

Related Questions