目前在 d3 v7 中使用 angular 7。嘗試在表格的每個單元格中呈現面積圖(如下圖所示)。但是使用 angular 方法渲染的 svg 會在回圈中保持渲染。不確定我在這里做錯了什么

HTML代碼
<tr [id]="'row' '-' fleet" *ngFor="let fleet of fleetcolumn">
<td>{{ fleet }}</td>
<ng-container *ngFor="let station of formattedBaseStations | slice: 1">
<td style="width: 28em;">
<div [id]="'demandChartInTable1-' station '-' fleet '-A'"> {{d3DemandChartIntable(station, fleet, 'A')}} </div>
</mat-grid-tile>
<mat-grid-tile class="FOChart">
<div [id]="'demandChartInTable1-' station '-' fleet '-B'"> {{d3DemandChartIntable(station, fleet, 'A')}} </div>
</mat-grid-tile>
</mat-grid-list>
</td>
</ng-container>
</tr>
.ts 代碼
d3DemandChartIntable(station, code, position) {
// set data
let temp1 = this.data
.filter(d => d.baseCode == station && d.code == code && d.position == position)
.map(d => {
return {
date: d3.timeParse('%Y-%m-%d')(d.date),
hours: d.hours
};
});
const e = document.querySelector('.captainChart');
// set the dimensions and margins of the graph
const margin = { top: 0, right: 0, bottom: 1, left: 1 },
width = 120 - margin.left - margin.right,
height = 90 - margin.top - margin.bottom;
// append the svg object to the body of the page
const svg = d3
.select(`#demandChartInTable1-${station}-${fleet}-${position}`)
.append('svg')
.attr('width', e.clientWidth margin.left margin.right)
.attr('height', e.clientHeight margin.bottom)
.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
const x = d3
.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, e.clientWidth]);
// Y axis
const y = d3
.scaleLinear()
.domain([0, 500])
.range([e.clientHeight margin.bottom, 0]);
// Add the area
return svg
.append('path')
.datum(temp1)
.attr('fill', '#cce5df')
.attr('stroke', '#69b3a2')
.attr('stroke-width', 1.5)
.attr(
'd',
d3
.area()
.x(d => x(d.date))
.y0(y(0))
.y1(d => y(d.hours))
);
}
上面的代碼在每個單元格中呈現重復的 svg 而不是只呈現一次

任何幫助將不勝感激
uj5u.com熱心網友回復:
關鍵在于以下代碼:
const svg = d3
.select(`#demandChartInTable1-${station}-${fleet}-${position}`)
.append('svg')
它選擇表格單元格,然后附加一個 SVG 元素。這意味著如果一個 SVG 已經存在,則會在它旁邊添加另一個。如果你想解決這個問題,你可以
- 選擇并更新現有的 SVG 并且只創建一次(例如在
ngOnInit或 中ngAfterViewInit); - 洗掉任何現有的 SVG 并繪制一個新的,使用
const cell = d3.select(`#demandChartInTable1-${station}-${fleet}-${position}`);
cell.remove('*');
const svg = cell.append('svg')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369898.html
上一篇:d3js多線散點圖縮放
下一篇:使UIButton影像適合按鈕
