Map zoom and pan in d3 js v4 + scale limit - d3.js

I've got this d3 js map. I've tried to make such a simple thing as zoom
and pan and just stalled. Now only dots zooms (I use v4). How to 'synchronize' zoom and pan of dots and map svg?
How to set limits of zoom and pan in d3 v4? I want it to be like this
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.style("border","none")
.style("background-color", "none")
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform)
}))
.append("g");

The circles scale but the paths do not because of how you append them. First, let's see how you apply the zoom:
var svg = d3.select("body")
.append("svg")
...
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform)
}))
.append("g"); // returns a selection of a newly appended g element
So the selection svg is actually a g element. While zoom is called on the svg element (not svg selection) it modifies the svg selection (which is actually holds a g): svg.attr(("transform"....
When you append your paths you use var map = d3.select("svg").insert(... and create a new g to hold the paths. But - this g is not in or a child of the selection svg - so it is not updated: d3.select("svg") != svg in this case. Instead, use:
var map = svg.insert(... // we insert into the svg selection which holds a g
This way we are inserting elements into the parent g that is updated each zoom.
While this really is a second question, the solution is simple enough. A d3.zoom() behavior can be constrained by both scale and translate:
d3.zoom().scaleExtent([1,4]) // limit scale to full size or 4x size.
.translateExtent([[0,0],[width,height]]) // limit pan to original SVG dimensions
zoom.translateExtent([p1,p2]) takes two points, upper left and lower right. We can constrain based on these dimensions if your features don't extend past the SVG bounds when initially loaded with a scale of 1.
Here's an updated bin.

Related

d3 v6 pointer function not adjusting for scale and translate

I am upgrading my app from d3 v5 to v6 and am having an issue migrating the d3.mouse functionality. In my app I apply a transform to the top level svg group and use the zoom functionality to zoom and pan (scale and translate). When I double click on the screen I take the mouse position and draw a square.
Now I am replacing the d3.mouse function with d3.pointer. In my double click event I get the mouse position by calling d3.pointer(event). However this function is not producing a position that is relative to where my top level svg group is positioned and scaled. When I remove the translate and scale from the top level group, the position matches up.
In the older version of d3 I could call d3.mouse(this.state.svg.node()) and it would produce the exact position I clicked corrected for pan and scale. Is this available in version 6? If not, is there a clean way I can adjust for this? The new event object is coming through with a host of different position properties: pagex, offsetx, screenx, x. None of these is producing the position I clicked on. Is there a clean way to acheive this?
You could specify a container element which would factor in a zoom transform in v5 and earlier:
d3.mouse(container)
Returns the x and y coordinates of the current event relative to the specified container. The container may be an HTML or SVG container element, such as a G element or an SVG element. The coordinates are returned as a two-element array of numbers [x, y]. (source)
In d3v6 you can specify this by using the second parameter of d3.pointer:
d3.pointer(event[, target])
Returns a two-element array of numbers [x, y] representing the coordinates of the specified event relative to the specified target. event can be a MouseEvent, a PointerEvent, a Touch, or a custom event holding a UIEvent as event.sourceEvent.
...
If the target is an SVG element, the event’s coordinates are transformed using the inverse of the screen coordinate transformation matrix. If the target is an HTML element, the event’s coordinates are translated relative to the top-left corner of the target’s bounding client rectangle. (source)
So as far as I'm aware, you should be use:
d3.pointer(event,this.state.svg.node());
Instead of
d3.mouse(this.state.svg.node());
Here's a d3v6 example:
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 200);
var rect = svg.append("rect")
.attr("width",500)
.attr("height",200)
.attr("fill", "#eee")
var g = svg.append("g");
var zoomed = function(event) {
g.attr("transform", event.transform);
}
rect.call(d3.zoom().on("zoom",zoomed))
.on("click", function(event) {
var xy = d3.pointer(event,g.node());
g.append("circle")
.attr("r", 5)
.attr("cx", xy[0])
.attr("cy", xy[1])
.attr("fill","crimson");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.0.0/d3.min.js"></script>
Adapting this v5 example:
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 200);
var rect = svg.append("rect")
.attr("width",500)
.attr("height",200)
.attr("fill", "#eee")
var g = svg.append("g");
var zoomed = function() {
g.attr("transform", d3.event.transform);
}
rect.call(d3.zoom().on("zoom",zoomed))
.on("click", function() {
var xy = d3.mouse(g.node());
g.append("circle")
.attr("r", 5)
.attr("cx", xy[0])
.attr("cy", xy[1])
.attr("fill","crimson");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

How to set initial position and scale when using d3.zoom()

I have the following code working;
const svg = d3
.select("svg")
.call(
d3
.zoom()
.wheelDelta(this.delta)
.on("zoom", function() {
svg.attr("transform", d3.event.transform);
})
)
.append("g")
.attr("id", "tree-container");
I later add a d3 tree layout insode the g.tree-container. The initial tree node is drawn in top left. Ideally I would like the initial node somewhere near the center of the svg
I have look here;
D3.js Set initial zoom level
but can't get it to work with my code and I don't really understand what is going on.
(i believe i am using d3 version 5.7)

Modifiying dimple layout grouped chart

I am using the same chart as below. I want to push the x-axis headers i.e. Regular, Premium, Budget little bit below i.e. top padding or margin. Give some styling to it like give background color and change text color. I tried using fill and it does not work as desired. I would like to hide Price Tier/Channel also
http://dimplejs.org/examples_viewer.html?id=bars_vertical_grouped
These are SVG text elements so there is no top-padding or margin. You can move them down a bit by increasing the y property though, running the following after you call the chart.draw method will move the labels down 5 pixels:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.attr("y", function (d) {
// Get the y property of the current shape and add 5 pixels
return parseFloat(d3.select(this).attr("y")) + 5;
});
To change the text colour you need to use the fill property (again that's an svg text thing):
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.style("fill", "red");
To colour the background of the text is a little less trivial, there actually isn't a thing for that in SVG, however you can insert a rectangle behind the text and do what you like with it:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
// Iterate each shape matching the selector above (all the x axis labels)
.each(function () {
// Select the shape in the current iteration
var shape = d3.select(this);
// Get the bounds of the text (accounting for font-size, alignment etc)
var bounds = shape.node().getBBox();
// Get the parent group (this the target for the rectangle to make sure all its transformations etc are applied)
var parent = d3.select(this.parentNode);
// This is just the number of extra pixels to add around each edge as the bounding box is tight fitting.
var padding = 2;
// Insert a rectangle before the text element in the DOM (SVG z-position is entirely determined by DOM position)
parent.insert("rect", ".dimple-custom-axis-label")
// Set the bounds using the bounding box +- padding
.attr("x", bounds.x - padding)
.attr("y", bounds.y - padding)
.attr("width", bounds.width + 2 * padding)
.attr("height", bounds.height + 2 * padding)
// Do whatever styling you want - or set a class and use CSS.
.style("fill", "pink");
});
These three statements can all be chained together so the final code will look a bit like this:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.attr("y", function (d) { return parseFloat(d3.select(this).attr("y")) + 5; })
.style("fill", "red")
.each(function () {
var shape = d3.select(this);
var bounds = shape.node().getBBox();
var parent = d3.select(this.parentNode);
var padding = 2;
parent.insert("rect", ".dimple-custom-axis-label")
.attr("x", bounds.x - padding)
.attr("y", bounds.y - padding)
.attr("width", bounds.width + 2 * padding)
.attr("height", bounds.height + 2 * padding)
.style("fill", "pink");
});
FYI the dimple-custom-axis-label class was added in a recent release of dimple so please make sure you are using the latest version. Otherwise you'll have to find an alternative selector

Combining translate and rotate with D3

Quite possibly this repeats some of this SO question, but the code is overly-complicated and the OP hasn't added solution code. And this related question is no longer replicable.
I'm trying to figure out how to combine rotations and translations in the right order. It's possible to rotate around the origin as in this example. But when we follow this with a translation the original rotation is undone.
Is it possible to structure this for correct sequential application?
jsfidle code:
HTML:
<script src="http://d3.geotheory.co.uk/d3-transform.js"></script>
SVG:
var svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 300);
//Draw the Rectangle
var rect = svg.append("rect")
.attr("x", 0).attr("y", 0)
.attr("width", 50).attr("height", 100)
.style("fill", "purple");
var rotate = d3.svg.transform().rotate(-45);
var translate = d3.svg.transform().translate(200, 100);
rect.attr('transform', rotate);
var rect2 = rect.attr('transform', rotate);
rect2.attr('transform', translate);
If you're looking to do this in D3 version 4.x+ you can do it like so:
.attr('transform', 'translate(200,100)rotate(-45)')
https://bl.ocks.org/mbostock/1345853
You're creating two different transformations. Assigning one doesn't add to the other. That is, in doing
rect2.attr('transform', translate);
you're undoing the first one, as it is overwritten.
To have both, add them both to one transition, e.g.
var rotateTranslate = d3.svg.transform().rotate(-45).translate(200, 100);
rect2.attr('transform', rotateTranslate);
To do this dynamically, you'll need to do something like this.
.attr("transform", function() {
return d3.svg.transform()
.translate(200, 100)
.rotate(-45)
.translate(-d3.select(this).attr("width")/2, -d3.select(this).attr("height")/2)();
}
Complete jsfiddle here.

D3JS scaling and transition performance

I have some code to scale and translate a map in D3 but the performance is quite terrible. When zooming and panning, it's taking nearly 3 seconds for a refresh. I thought the map would look nicer including line boundaries for all the counties, but at 6MB+ I suspect this may be where the bottleneck is coming from. Is there another way I should be handling the transforms or maybe a way to optimize the map data? Is D3 really not suited to this level of detail? Very new to D3.
I'm using shape files from here, converted from DBF to Geojson using QGIS:
https://www.census.gov/cgi-bin/geo/shapefiles2010/main
<!doctype html>
<html>
<head>
<title>d3 map</title>
<script src="http://d3js.org/d3.v3.min.js">
</script>
</head>
<body>
<script>
var width = 800;
var height = 600;
var projection = d3.geo.mercator();
var path = d3.geo.path().projection (projection);
var canvas = d3.select ("body")
.append ("svg")
.attr ("width", width)
.attr ("height", height)
var zoomVar = d3.behavior.zoom()
.translate(projection.translate())
.scale(projection.scale())
.scaleExtent([height, 60 * height])
.on("zoom", onPostZoom);
var hotbox = canvas.append("g").call(zoomVar);
hotbox.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("fill", "white")
.attr("height", height);
d3.json ("cali.geojson", function (data)
{
hotbox.append("g")
.attr("id", "geometry")
.selectAll("path")
.data(data.features)
.enter()
.append("path")
.attr("d", path)
.attr("fill", "steelblue")
.on("click", onClick);
})
function onClick (d)
{
var centroid = path.centroid(d), translate = projection.translate();
projection.translate(
[translate[0] - centroid[0] + width / 2,
translate[1] - centroid[1] + height / 2 ]);
zoomVar.translate(projection.translate());
hotbox.selectAll("path").transition()
.duration(700)
.attr("d", path);
}
function onPostZoom()
{
projection.translate(d3.event.translate).scale(d3.event.scale);
hotbox.selectAll("path").attr("d", path);
}
</script>
</body>
</html>
As Lars said, you should definitely simplify your data to the appropriate resolution. Choose the maximum resolution based on how far you want to zoom in. I recommend topojson -s to simplify, as you’ll also get the benefits of the smaller TopoJSON format.
The other big thing is to avoid reprojection if you’re just panning and zooming. Reprojection is a comparatively expensive trigonometric operation, and so is serializing very large path strings in SVG. You can avoid this for panning and zooming (translating and scaling) by simply setting the transform attribute on the path elements or a containing G element. See these examples:
Zoom to Bounding Box
Raster & Vector Zoom
You should also consider using projected TopoJSON (alternate example) which bakes the projection into the TopoJSON file. This makes the client is even faster: it never has to project!
The problem you're experiencing isn't really because of D3, but because of the browser. The main bottleneck is rendering all the visual elements, not computing their positions etc.
The only way to avoid this is to have less data. One way to start would be to simplify the boundaries in QGIS, using e.g. the dpsimplify plugin.

Resources