如何使用D3J和Angular 7构建简单的甜甜圈图



我使用d3.js v5在角度创建甜甜圈图。所有其他简单的图形,例如bar graph,圆圈,线路等。正常工作,但是" pie()函数都会出现一些错误。谁能建议我如何使用pie()在Angular中正常功能?

我在下面提到的方案中遇到错误。

  1. 在设置颜色域时,它不接受数据,它需要ReadOnlyArray<String>,因此尝试提供硬编码域["a","b","c","d","e"]

  2. pie()->不接受值,不知道为什么在这里尝试了很多。

  3. this.color(d.data.key))-> this.color不接受访问数据和键。

需要解决上述所有问题。

代码如下:

export class DonutChartComponent implements OnInit {
    width = 450
    height = 450
    margin = 40
    radius;
    svg;
    color;
    pie;
    data_ready;
    // Create dummy data
    public data = {a: 9, b: 20, c:30, d:8, e:12}

    constructor() { }
    ngOnInit() {
    this.draw();
    }

     draw(){
     this.radius = Math.min(this.width, this.height) / 2 - this.margin

     this.svg = d3.select("app-donut-chart")
               .append("svg")
               .attr("width", this.width)
               .attr("height", this.height)
               .append("g")
               .attr("transform", "translate(" + this.width / 2 + "," + 
                this.height / 2 + ")");

     // set the color scale
     this.color = d3.scaleOrdinal()
            .domain(this.data)             // this.data gives error here
           .range(d3.schemeDark2);
     console.log(d3.scaleOrdinal());
     // Compute the position of each group on the pie:
     this.pie = d3.pie()
               .value(function(d) {return  d.values});     //error here
     this.data_ready = this.pie(d3.entries(this.data))
      this.svg
     .selectAll('whatever')
     .data(this.data_ready)
     .enter()
     .append('path')
     .attr('d', d3.arc()
     .innerRadius(100)         // This is the size of the donut hole
     .outerRadius(this.radius))
     .attr('fill', function(d){ return(this.color(d.data.key)) })  
                                                           //error here
     .attr("stroke", "black")
     .style("stroke-width", "2px")
     .style("opacity", 0.7)
    }
}

我希望如果代码正确运行,我可以根据给出的数据看到一个甜甜圈图。

夫妇错误:

  1. 您的颜色秤的.domain期望字符串列表。修改为:

    .domain(Object.keys(this.data))

  2. 您的派生成器应定义为:

    this.pie = d3.pie() .value(function (d) { return d.value })

现在起作用。

this.radius = Math.min(this.width, this.height) / 2 - this.margin;
    this.svg = select("pie-chart")
      .append("svg")
      .attr("width", this.width)
      .attr("height", this.height)
      .append("g")
      .attr("transform", "translate(" + this.width / 2 + "," +
        this.height / 2 + ")");
    this.color = scaleOrdinal()
      .domain(Object.keys(this.data))
      .range(schemeDark2);
    console.log(scaleOrdinal());
    this.pie = pie()
      .value((d) => d.valueOf());
    this.dataReady = this.pie(entries(this.data));
    this.svg
     .selectAll("whatever")
     .data(this.dataReady)
     .enter()
     .append("path")
     .attr("d", arc()
     .outerRadius(this.radius))
     .attr("fill", (d) => (this.color(d.data.key)))
     .attr("stroke", "black")
     .style("stroke-width", "2px")
     .style("opacity", 0.7);

最新更新