如何使用新数据更新 d3 图表: 我正在 ngOnchanges 上实现三个函数:
this.removeSvg(this.data);
this.createSvg();
this.drawBars(this.data);
其中 createSvg() :
private createSvg(): void {
this.svg = d3.select("figure#histogram")
.append("svg")
.attr("width", '100%')
.attr("height", '100%')
.append("g")
.attr("transform", "translate(" + this.margin + "," + this.margin + ")");
}
和removeSvg():
this.svg = d3.select("figure#histogram")
.exit().remove()
d3.select("#histogram").select("svg").remove();
和drawBars(数据:任何[]):
private drawBars(data: any[]): void {
// Create the X-axis band scale
const x = d3.scaleBand()
.range([this.axisMin, 340])
.domain(data.map(d => d.xAxis))
.padding(0);
// Create the Y-axis band scale
const y = d3.scaleLinear()
.domain([0, this.axisMax])
.range([this.height, 0])
.nice();
// Create and fill the bars
this.svg.selectAll("bars")
.data(data)
.enter()
.append("rect")
.attr("x", d => x(d.xAxis))
.attr("y", d => y(d.yAxis))
.attr("width", x.bandwidth())
.attr("height", (d) => this.height - y(d.yAxis))
.attr("fill", "rgb(13, 185, 240)");
}
但它不会刷新图表,即使我确定数据正在刷新(因此对于第一个图表,我们继续拥有所有其他图表,就好像它是相同的数据一样) 有什么帮助吗?也许删除或退出在这里是错误的!
最佳答案
在 D3 中,可以通过选择来操作 DOM。在 drawBars()
函数中,您使用 enter
选择来描述新数据会发生什么。
要描述已更改的数据会发生什么情况,请使用更新
选项;对于离开的数据,请使用退出
选择。要跟踪更新的数据,您需要在 data()
调用上使用一个关键函数来唯一标识每个元素。
See this tutorial以获得更深入的概述。
在您的drawBars()
函数中:
private drawBars(data: any[]): void {
// ...
let t = svg.transition().duration(500);
this.svg.selectAll("bars")
.data(data, d => d)
.join(
enter => enter
.append("rect")
.attr("x", d => x(d.xAxis))
.attr("y", d => y(d.yAxis))
.attr("width", x.bandwidth())
.attr("height", (d) => this.height - y(d.yAxis))
.attr("fill", "rgb(13, 185, 240)"),
update => update.call(update => update.transition(t)
.attr("x", d => x(d.xAxis))
.attr("y", d => y(d.yAxis))
.attr("height", (d) => this.height - y(d.yAxis))),
exit => exit.call(exit => exit.transition(t)
.attr("x", 0)
.attr("y", 0)
.attr("height", 0)
.remove()))
}
关于javascript - 收到新数据时如何更新 d3 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63249124/