【发布时间】:2019-02-14 14:41:05
【问题描述】:
我正在使用 D3.js v5 在 Angular 中创建一个圆环图。所有其他简单的图形,如条形图、圆形、线条等都可以正常工作,但“pie()”函数会出现一些错误。谁能建议我如何在 Angular 中正确使用 pie() 函数?
我在以下提到的场景中遇到错误。
在设置颜色域时,它不接受数据,它说,它需要
ReadOnlyArray<String>,所以尝试给硬编码域["a","b","c","d","e"]pie()--> 不接受值,不知道为什么,在这里尝试了很多。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)
}
}
我希望如果代码运行正常,我可以根据给定的数据看到一个圆环图。
【问题讨论】:
标签: angular d3.js angular7 donut-chart