Beginner in d3, making US county map - javascript

So I've been given an assignment where I need to work with the US map, divided into states and further into counties. I already have the current code and need to extend on it.
I am not able to understand the following snippet from the code.
var colorRange = [ 'rgb(247,251,255)',
'rgb(222,235,247)',
'rgb(198,219,239)',
'rgb(158,202,225)',
'rgb(107,174,214)',
'rgb(66,146,198)',
'rgb(33,113,181)',
'rgb(8,81,156)',
'rgb(8,48,107)'];
var quantile = d3.scale.quantile()
.range(colorRange);
var path = d3.geo.path();
var svg = d3.select("#map")
.attr("width", width)
.attr("height", height)
.append('svg:g')
.call(d3.behavior.zoom().on("zoom", redraw))
.append('svg:g');
svg.attr("transform", "scale( " + .9 + ")");
function redraw() {
console.log("here", d3.event.translate, d3.event.scale);
svg.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")");
}
What exactly is happening in each line of this snippet?
Full Code taken from here
Thanks

the var colorRange is just a variable holding the colors to be applied to the various counties, the var quantile sets the scale for the color to be applied, the var path calls the path function and the var svg creates an svg. In this the command .call has a functionality .on("zoom", which calls the function redraw.
function redraw defines the function, which translates and scales the svg accordinglly to the zoom

Related

Zoom/Pan D3.js Polar Scatter Plot

I created a polar scatter plot using D3.js (based on this post) .
I would like to add the functionality to zoom and pan. I've seen examples for rectangular plots, but nothing for zooming/panning on circular plots.
I am just a beginner with using D3 so I'm a little lost. Can anyone help/offer suggestions?
I'm not entirely sure what your goal is, but I tried something below.
First you should add zoom behaviour. I used the r scale for both your x and y directions like:
var zoomBeh = d3.behavior.zoom()
.x(r)
.y(r)
.on("zoom", zoom);
And call the zoom behaviour into your svg:
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.call(zoomBeh);
Finally you should make a zoom function.
function zoom() {
var t = svg.transition().duration(750);
svg.selectAll(".point").transition(t)
.attr("transform", function(d) {
var coors = line([d]).slice(1).slice(0, -1);
return "translate(" + coors + ")"
})
}
Here is an updated fiddle. It's a little bit staggering, I'm not sure why yet.

Zooming functionality in d3 - running slowly

So, I have a work-able d3 map but the only problem is the zoom is incredibly slow. This is a map of about 200 points on the globe where I'd like to be able to zoom in/pan and retreive info on each point. I think d3 looks so much better than leaflet, but for quick zooming/panning functionality, my first question is: is this better off in leaflet or can d3 handle slick zoom/pan even though it's not tile-based?
I've included a snippet of my code below: am I doing something wrong here? It works as is, but is there a way to make the zoom run more quickly? Thanks in advance! Everyone here has been so helpful.
function zoomed() {
console.log("zooming now!")
///called on zoom events
d3.selectAll(".centroid").attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
d3.selectAll(".gratLines").attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
d3.selectAll(".countries").attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
d3.selectAll(".gratBackground").attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
};
function setMap() {
var zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.scaleExtent([1, 21])
.on("zoom", zoomed);
console.log("setting map")
var map = d3.select("body")
.append("svg")
.attr("width", mapWidth)
.attr("height", mapHeight)
.attr("class", "map")
var pageTitle = d3.select("body")
.append("text")
.attr("class", "pageTitle")
.html("UW Hospital Graduates:<br>Where Do They Go?");
var projection = d3.geo.naturalEarth()
.scale(410)
.translate([mapWidth / 2, mapHeight / 2])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var path = d3.geo.path()
.projection(projection)
.pointRadius(3);
//create graticule generator
var graticule = d3.geo.graticule();
//create graticule background (aka water)
var gratBackground = map.append("path")
.datum(graticule.outline)
.attr("class", "gratBackground")
.attr("d", path)
zoom.on('zoom', zoomed)
map.call(zoom);
var gratLines = map.selectAll(".gratLines")
.data(graticule.lines) //
.enter()
.append("path") //append one path for each element of the data (in this case, each graticule line)
.attr("class", "gratLines")
.attr("d", path) //this path is the variable path defined above. path generator

How do I fix zooming and panning in my cluster bundle graph?

I've created a hierarchical edge bundling graph with some data and after trying to implement zooming and dragging on the graph I've run into some issues.
Here is a similar working jsfiddle of what I have so far: https://jsfiddle.net/hnjvxd48/1/
and the relevant code:
var zoom = d3.behavior.zoom()
.scaleExtent([0,8])
.on("zoom", zoomhandler);
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
var svg = d3.select(".container").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")")
.call(zoom)
.call(drag);
function zoomhandler(){
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
You'll notice:
1) Dragging and zooming only occur on the outer edges and not the inner part of the graph.
2) Dragging the graph around causes flickering and centering of the graph to change and become cut off.
3) Zooming (done via mouse scroll wheel) also centers the graph incorrectly and places it in an unpredictable position, partly out of the view port.
4) Attempting to drag the graph after it has been zoomed out causes it to flicker and disappear.
What's causing these issues and how can I fix them? How can I give my graph (which is much bigger than the sample one I provided) an initially "zoomed out" state and perhaps trigger the zooming functionality using a button click event rather than the native scroll wheel implementation?
The big thing to notice here is that the drag functions are actually redundant. In this (http://bl.ocks.org/mbostock/6123708) d3 drag + zoom example, they're being used to move individual 'dots'. You want to move the whole graph at once, and this is handled by the 'translate' portion of the 'zoomhandler' function you've included.
Here's a working fiddle: https://jsfiddle.net/14f9f4k3/1/
And the key code that with changes noted in comments:
var zoom = d3.behavior.zoom()
.scaleExtent([0,8])
.on("zoom", zoomhandler);
//added another group as a child of the group having zoom called on it w/ id 'draggroup' to append nodes and links to
var svg = d3.select(".container").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")")
.call(zoom)
.append('g')
.attr('id','draggroup');
//added a rect behind the other elements to make an easy target for the pointer
d3.select('#draggroup')
.append('rect')
.attr("transform", "translate(" + -radius + "," + -radius + ")")
.attr('width',diameter)
.attr('height',diameter)
.attr('fill','#fff');
//no need for separate drag functions, translate and scale here do what you want
function zoomhandler(){
svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
}
//append the links and nodes to the group we created above instead of the base svg
var link = d3.select('#draggroup').append("g").selectAll(".link"),
node = d3.select('#draggroup').append("g").selectAll(".node");

In D3 how to enable zooming only for particular path?

I created a d3 geomap. In that i enabled zooming feature by using d3.behaviour.zoom().
Actually, zooming part is working fine.But my problem is i need to zoom only background layer.
I mean i created a world map. In that over the each country i created a circle. So while zooming i need to increase the world map size not that circle. I need to show same size of circle always.
Please help me to solve this .Also, i added fiddle link below.Kindly take a look and help me.
Fiddle Link - http://jsfiddle.net/sam0kqvx/39/
The zoom behaviour does what you tell it to. In your fiddle:
function zoom() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
Notice that scaling and translation is performed over the whole svg. You need to define another variable that has .countries without .dots and perform the zoom only on .countries
First, apply the zoom only on the <g> that contain .countries
var countries = svg.append("g") //apply zoom here.
.call(d3.behavior.zoom().scaleExtent([1, 8])
.on("zoom", zoom))
.selectAll(".countries")
.data(topojson.feature(world, world.objects.countries).features)
.enter()
Then, in zoom function, scale and translate only the selected elements this
function zoom() {
d3.select(this).attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
Here is your updated fiddle
Note:
Disabling the zoom behaviour from the circles will also disable panning, which means that the user can slide the map from under the circles. You need to handle this as well.
=============
Another solution is to reverse scale the circles sizes in the zoom function, as mentioned in the comment.
function zoom() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
svg.selectAll("circle").attr("r", 6/d3.event.scale);
}
Here is the fiddle for it.
If circle sizes are variable:
You can store the "true radius" is a separate attribute and replace 6/d3.event.scale by trueR/d3.event.scale
Here are the 2 updates in your fiddle.
//Store the original raduis is a "trueR" attributes
svg.selectAll(".dots")
.data(topojson.feature(world, world.objects.countries).features)
.enter()
.append("circle")
.attr("r",function(d,i){
radius = Math.random()*20;
return radius;
})
.attr("trueR", function(d){ return d3.select(this).attr("r")})
.attr("fill","black")
.attr("transform",function(d){
var p = projection(d3.geo.centroid(d));
return "translate("+p+")";
});
//Use "trueR" in the zoom() function
function zoom() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
svg.selectAll("circle").attr("r", function(d){
return (d3.select(this).attr("trueR"))/d3.event.scale;
});
}
Update fiddle

How to apply d3.js svg clipping after zooming

I am trying to use an svg-clippath with d3.js and the zoom behaviour.
The following code creates a rectangle, which will then be clipped by a rectangualar clipping region.
<svg class="chart"></svg>
<script>
var width = 800;
var height = 600;
var svg = d3.select(".chart")
.attr("width", width)
.attr("height", height)
.append("g");
var clip = svg.append("defs")
.append("clipPath")
.attr("id","clip")
.append("rect")
.attr("width",200)
.attr("height",200)
.attr("x",100)
.attr("y",100);
var zoom = d3.behavior.zoom().
on("zoom",zoomed);
function zoomed(){
container.attr("transform", "translate(" + d3.event.translate
+")scale(" + d3.event.scale + ")");
container.attr("clip-path","url(#clip)");
}
svg.call(zoom);
var container = svg.append("g")
.attr("clip-path","url(#clip)");
var rect = container.append("rect")
//.attr("clip-path","url(#clip)")
.attr("class","bar")
.attr("x",150)
.attr("y",150)
.attr("width",350)
.attr("height",350);
</script>
What I want is for the clipping to be applied again after zooming / moving (so that I cannot
move the rectangle outh of the clipping region, which right now i can do without any problems.) How do I do that?
I am assuming that the current behaviour is caused by the fact that the clipping is applied before the transformation.
I had the same problem and spent the last couple of hours trying to figure out a solution. Apparently, the clip-path operates on the object prior to transformation. So I tried to reverse-transform the clip object when performing the zoom transformation, and this worked !
It is something in the spirit of:
var clip_orig_x = 100, clip_orig_y = 100;
function zoomed() {
var t = d3.event.translate;
var s = d3.event.scale;
// standard zoom transformation:
container.attr("transform", "translate(" + t +")scale(" + s + ")");
// the trick: reverse transform the clip object!
clip.attr("transform", "scale(" + 1/s + ")")
.attr("x", clip_orig_x - t[0])
.attr("y", clip_orig_y - t[1]);
}
where clip is the rectangle in the clipPath. Because of interactions between zooming and translation, you need to set "x" and "y" explicitly instead of using transform.
I am sure experienced d3 programmers out there will come up with a better solution, but this works !

Categories

Resources