我正在使用 D3.js v5 在 Angular 中创建一个 donut chart 。所有其他简单的图形,如条形图、圆、线等都可以正常工作,但是“pie()”函数会出现一些错误。谁能建议我如何在 Angular 中正确使用 pie() 函数?
我在下面提到的场景中遇到错误。
ReadOnlyArray<String>
,所以尝试给出硬编码域 ["a","b","c","d","e"]
pie()
--> 不接受值,不知道为什么,在这里尝试了很多。 this.color(d.data.key))
--> this.color
不接受访问数据和 key 。 需要解决上述所有问题。
代码如下:
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)
}
}
我希望如果代码运行正常,我可以看到基于给定数据的圆环图。
最佳答案
一些错误的地方:
.domain
期待一个字符串列表。修改为:.domain(Object.keys(this.data))
this.pie = d3.pie()
.value(function (d) { return d.value })
现在它works .
关于angular - 如何使用 D3js 和 Angular 7 构建一个简单的 donut chart ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54692979/