I'm using D3 and React to plot a simple line chart with Zoom and Pan behavior. 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%].
I tried to keep a copy of my original dataset and update the viewportDataset on zoom:
_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:
_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.
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));
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.