score:1
Accepted answer
There's actually an example of a programmatic zoom right in the code you are looking at:
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
So, say we stored our "view" JSON in terms of zoomed to dates:
["2003-06-12T19:24:00.000Z","2006-05-20T19:24:00.000Z"]
Loading it would simply be:
d3.json("viewData.json", function(error, data) {
var d = data.map(function(d){
return new Date(d);
})
svg.select(".zoom")
.transition()
.call(zoom.transform, d3.zoomIdentity
.scale(width / (x(d[1]) - x(d[0])))
.translate(-x(d[0]), 0)
);
});
Here's a running example.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.area {
fill: steelblue;
clip-path: url(#clip);
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
</style>
<svg width="700" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 110, left: 40},
margin2 = {top: 430, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
height2 = +svg.attr("height") - margin2.top - margin2.bottom;
var parseDate = d3.timeParse("%b %Y");
var x = d3.scaleTime().range([0, width]),
x2 = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x),
xAxis2 = d3.axisBottom(x2),
yAxis = d3.axisLeft(y);
var brush = d3.brushX()
.extent([[0, 0], [width, height2]])
.on("brush end", brushed);
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var area = d3.area()
.curve(d3.curveMonotoneX)
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.price); });
var area2 = d3.area()
.curve(d3.curveMonotoneX)
.x(function(d) { return x2(d.date); })
.y0(height2)
.y1(function(d) { return y2(d.price); });
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
d3.json("https://jsonblob.com/api/8737d329-6f32-11e7-9e0d-efd5dcec6244", function(error, data) {
if (error) throw error;
data.forEach(type);
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.price; })]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area);
focus.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
context.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area2);
context.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
});
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
var s = d3.event.selection || x2.range();
x.domain(s.map(x2.invert, x2));
focus.select(".area").attr("d", area);
focus.select(".axis--x").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
}
function zoomed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
var t = d3.event.transform;
x.domain(t.rescaleX(x2).domain());
focus.select(".area").attr("d", area);
focus.select(".axis--x").call(xAxis);
context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
}
function type(d) {
d.date = new Date(d.date);
d.price = +d.price;
return d;
}
d3.select('body')
.append('button')
.style('margin', '20px')
.text('Load View')
.on('click', function(){
d3.json("https://jsonblob.com/api/b580e2b9-6f32-11e7-9e0d-97f11fab6446", function(error, data) {
var d = data.map(function(d){
return new Date(d);
})
svg.select(".zoom").transition().call(zoom.transform, d3.zoomIdentity
.scale(width / (x(d[1]) - x(d[0])))
.translate(-x(d[0]), 0));
});
})
</script>
Source: stackoverflow.com
Related Query
- D3 v4 Brush and Zoom on the same element (without mouse events conflicting)
- d3 zoom and brush working at the same time
- d3.js pan and zoom jumps when using mouse after programatic zoom
- D3 Brush and Zoom error
- D3js v5 Trying to select multiple bars in bar chart using brush and saving values to variable and table
- D3 v4 - Brush and Zoom - rescale y axis
- D3 Canvas brush and zoom
- In my d3 chart, Zoom selection disappears when I change the brush and click on not selected range
- Brush and Zoom d3
- d3 using zoom and brush on a bar chart
- D3: Unit Bar Chart with Brush and Zoom (transpose)
- saving and restoring "brush & zoom"? (programatic zoom)
- d3 v3 - sync brush zoom and scroll zoom
- Recording and saving an SVG animation as an animated GIF
- Achieving animated zoom with d3 and Leaflet
- d3 zoom and pan upgrade to version 4
- Saving and reloading a force layout using d3.js
- brush on rotated lines using d3 to create zoom effect
- Mouse events and brush in D3
- d3.js click and apply zoom and pan to distribute points located inside a targeted division to the triggered subdivisions
- Unusual d3 zoom in reusable class - this and bind
- D3 click coordinates after pan and zoom
- D3 - How to get correct scale and translate origin after manual zoom and pan to country path
- d3 zoom difference between Chrome and Firefox
- How to use mouse click and drag to zoom in D3
- D3 Zoom with Scrollbars used as panning, Scrollbar width and height adjusts to zoom scale
- Constrain zoom and pan in d3
- how do i add a zoom in and zoom out button in a graph on d3
- javascript d3.js: initialize brush with brush.extent and stop data from spilling over margin
- Restricting minimum and maximum width of brush box
More Query from same tag
- Tracking d3.zoom transform across page refresh
- Text on vertical bars not showing using d3.js
- D3 Responsive chart
- Updating a choropleth map with a dropdown button
- How do I add an SVG line over a css style
- Update donut chart using the c3 library (JQuery)
- D3 how do you center an element with pan/zoom enabled?
- Plotly.js Adding markers adds padding to x-axis
- d3: how to interpolate a string (with numbers in it) so that the numbers don't get interpolated
- How do I get the coordinate of a d3 line?
- How to debug when get error from D3
- Remove end-ticks from D3.js axis
- d3.event is getting null in typescript implementation
- D3 bring a circle to top?
- D3 creating bar chart from big csv
- how to draw horizontal line in y axis in d3 column chart?
- place image inside grid using d3js
- refactoring d3 js code from v5.16 to v6.6.2, d3.event breaking change
- Tooltip in worldmap created via d3.js
- update d3 in browser from python
- draw circle in the end of SVG path in realtime line chart D3.js
- Finding Offset Position of SVG Element
- d3 svg differentiate onclick
- where can I download this code
- D3 Scale domain does not update with selected data. I get negative values
- d3js text not showing on node graph
- d3js charts, Use json strings instead of json file
- add color to node dagre d3
- D3: "SVG4601: SVG Path data has incorrect format and could not be completely parsed."
- d3 map tutorial - converting shp data