D3 V4饼图Angular2打字稿路径不正确

时间:2017-12-14 17:58:25

标签: angular d3.js

我有一个工作Angularjs D3v3饼图,并已决定将其移植到Angular5,并将其更新为D3 V4。我正在获取数据,但弧线基本上是空的,我无法说明原因。

以下是我的代码片段:

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");
}

我知道有些东西我没有看到,任何帮助都会受到赞赏。 完整代码在此处:Pie Chart D3 V4

1 个答案:

答案 0 :(得分:1)

我认为错误是在您定义pie时。

当我改变这个时:

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

对此:

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

我在plunkr

上找到一个饼图