[英]Update data while zooming with D3 and React
I'm using D3 and React to plot a simple line chart with Zoom and Pan behavior. 我正在使用D3和React绘制具有缩放和平移行为的简单折线图。 I need to make the data to be relative to the first value on the actual zoom.
我需要使数据相对于实际缩放中的第一个值。
For example, if my dataset Y values are [0, 2%, 3% and 4%] and I'm currently viewing the last 3 values, it should plot [0, 1.02%, 2.04%]. 例如,如果我的数据集的Y值是[0、2%,3%和4%],而我当前正在查看最后3个值,则它应该绘制[0、1.02%,2.04%]。
I tried to keep a copy of my original dataset and update the viewportDataset on zoom: 我试图保留原始数据集的副本并在zoom上更新viewportDataset:
_onZoom (zoom) {
let state = this.state,
data = state.data,
viewportData = [],
filteredData,
y = state.y,
x = state.x,
minDate = d3.min(data, d => d.date),
maxDate = d3.max(data, d => d.date),
xZoom, yExtent, yDiff;
if (x.domain()[0] < minDate) {
xZoom = zoom.translate()[0] - x(minDate) + x.range()[0];
zoom.translate([xZoom, 0]);
}
else if (x.domain()[1] > maxDate) {
xZoom = zoom.translate()[0] - x(maxDate) + x.range()[1];
zoom.translate([xZoom, 0]);
}
filteredData = data.filter((d, i) => {
if ((d.date >= x.domain()[0]) && (d.date <= x.domain()[1])) {
return [d.daily, d.accumulated, d.dailyRelative];
}
});
let factor = filteredData[0].dailyRelative;
filteredData.map(d => {
d.dailyRelative = d.dailyRelative / factor;
viewportData.push(d);
});
y.domain(d3.extent(filteredData, d => d.dailyRelative));
this.setState({ y, viewportData });
}
React, after setting the new viewportData and Y scale, calls my updateChart chart function: 在设置新的viewportData和Y缩放比例后,React调用我的updateChart图表函数:
_updateChart () {
/* ... */
let line = chart
.select('g.data')
.selectAll('path.line')
.data([state.viewportData]);
line.attr('d', d => this._line(d));
line.enter().append('path.line')
.attr('d', d => this._line(d));
line.exit().remove();
}
This approach isn't working. 这种方法行不通。 I think I'm not doing the update pattern right.
我认为我没有正确执行更新模式。 How do I achieve this behavior?
如何实现这种行为? I ported my working chart into a pen, heres the code
我将工作图表移植到笔中, 代码如下
I ended up updating the data after the zoom event, duh. 我结束了缩放事件之后的数据更新,du。
Not quite the behavior I was looking for but it's working. 并不是我一直在寻找的行为,但它正在起作用。
_onZoomend () {
/* ... */
chart.select('g.data path.line')
.transition()
.attr('d', d => this._line(d, factor));
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.