d3.v3 transitions happening instantly? - d3.js

I've recently passed from d3.v2 to d3.v3, and am trying to understand the differences in the transition mechanisms.
In the code underneath, I'm trying to make a bar graph that, when drawn, has bars that increase in height via a transition. This code works without issue in d3.v2, but in v3, the transition seems to happen "instantly" (the height is immediately set to the end value).
graph.enter()//for each bucket
.append('g')
.attr('transform',function(d,i){ return 'translate('+(xBand(i))+')';})
.attr('width',xBand.rangeBand())
.each(function(data,index){//here we are working on the selection for a single bucket
var $this=d3.select(this); //this refers to the group selection
var currentY=0;
var rects=$this.selectAll('rect')
.data(data.values);
rects.enter()
.insert('rect')
.attr('group-id',me.groupId)
.attr('y',Hats.accessor('y'))
.attr('width',xBand.rangeBand())
.attr('fill',(function(elt){ return me.colors(me.groupId(elt));}));
rects.transition()
.duration(750)
.attr('height',(function(elt){
var h=_.compose(heightScale,me.values)(elt);
d3.select(this).attr('y',currentY);
currentY+=h;
return h;
}));
});

Try setting a starting height in your enter selection:
rects.enter()
.insert('rect')
.attr('group-id',me.groupId)
.attr('y',Hats.accessor('y'))
.attr('width',xBand.rangeBand())
.attr('fill',(function(elt){ return me.colors(me.groupId(elt));}))
.attr('height', 0);
rects.transition()
.duration(750)
.attr('height',(function(elt){
var h=_.compose(heightScale,me.values)(elt);
d3.select(this).attr('y',currentY);
currentY+=h;
return h;
}));

Related

d3 (v4) zoom using transitions doesn't seem to work

I am using the d3 zoom behaviour and attempting to use a transition for both a translateTo and a scaleTo at the same time. If I make the calls to zoom without a transition everything works fine. If I use a transition for just one of the transforms it also works, but if I attempt to use a transition for both it fails (it appears to only apply the first transform). I have a JSFiddle with several combinations here: JSFiddle
Here's the code that isn't working as I expect
svg.transition()
.duration(750)
.call(zoom.scaleTo, 2)
.call(zoom.translateTo, 50, 50)
You can do like this:
svg.transition()
.duration(750)
.call(zoom.scaleTo, 2)
.transition() <--- this is missing.
.call(zoom.translateTo, 50, 50)
First zoom then translate.
working code here
EDIT
Performing zoom and translate both # same time you need to tween.
function twizzle(selection, duration) {
d3.select(selection).transition()
.duration(duration)
.tween("attr:transform", function() {
//interpolate from start to end state
var i = d3.interpolateString("scale(1)translate(0,0)", "scale(2)translate(50,50)");
return function(t) {
selection.attr("transform", i(t));
};
});
}
Now call the function like this:
d3.select('body')
.append('button')
.text('transition both - scale first')
.on('click', function() {
//on click call the function created above
group.call(twizzle, 750) <-- perform the scale and translate on the group not on the SVG.
})
working code here

D3 Selection Highlight (efficiency?)

I have a simple visual of many rects, over 100 I'd say. For aesthetic purposes I want to create a high light effect on mouse click. I also wanted to make this effect somewhat intuitive by removing that effect once the user clicks on a new rect. However I couldn't get this to work without resorting to a d3.selectAll() call, so I'm thinking this approach might not be ideal if this project gets any bigger. Here is the code:
.on('click.highlight', function() {
//set any previously highlighted rects back to normal color/brightness
d3.selectAll('.highlight').transition().duration(250)
.style('fill', function(d) { return d3.rgb(d.color)})
d3.select(this).classed('highlight',true);
//now it's safe to assign the current highlighted rect a brighter hue... i think
d3.select(this).transition().duration(250)
.style('fill', function(d) { return d3.rgb(d.color).brighter(.5)})
})
Though this code does what I wanted it to do, but presumably there could only ever be 1 other highlight rect to worry about at any give time. So again, I'm not sure that using d3.selectAll() is warranted here.
So anyway, is there a more efficient way? I'd like to keep it all within one .on('click') function if possible.
If you are looking to avoid use of .selectAll, you could create a selection of one rect that contains the last clicked rectangle. Each time you click on a rectangle:
unhighlight the previously selected highlighted rect
update that selection to reflect the most recently clicked rectangle
highlight the newly selected rect
I use the variable highlightedRect to hold the selection that will allow the above workflow:
var svg = d3.select("body").append("svg")
.attr("width",600)
.attr("height",400);
var highlightedRect = d3.select(null);
var rects = svg.selectAll("rect")
.data(d3.range(1600))
.enter()
.append("rect")
.attr("y",function(d) { return Math.floor(d/50)*12; })
.attr("x",function(d) { return d%50 * 12 })
.attr("width",11)
.attr("height",11)
.attr("stroke","white")
.on("click",function(d) {
// Recolor the last clicked rect.
highlightedRect.attr("fill","black");
// Color the new one:
highlightedRect = d3.select(this);
highlightedRect.attr("fill","steelblue");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

D3-Force updating parameters after initializing graph

In D3 v4 with the force module, how do you update the parameters of the simulation once you have initialized the graph?
More precisely, I am trying to change the .forceLink and .forceManyBody of the force directed graph when the user clicks one of its nodes.
var node = svg
.append("g")
.attr("class", "gnodes")
.selectAll(".node")
.data(graph.nodes)
.enter()
.append("g")
.attr("class", "node")
.on('dblclick', connectedNodes); //calls for change in simulation parameters
So far I have been able to update it by duplicating the simulation under the connectedNodes function:
function connectedNodes() {
//new parameters
linkDistance = 5;
fCharge = -10;
//replicates the initial simulation code
simulation = d3.forceSimulation()
.force("link", d3.forceLink()
.id(function(d) {return d.id;})
.distance(linkDistance)
)
.force("collide", d3.forceCollide()
.radius(function(d){return d.r + 10})
.strength(1)
)
.force("charge", d3.forceManyBody()
.strength(fCharge)
)
.force("center", d3.forceCenter(width / 2, height / 2));
simulation.nodes(graph.nodes).on("tick", ticked);
simulation.force("link").links(graph.links);
Although this works it is very redundant. Is there a way in which the simulation can be refreshed with the new parameters? I have tried the following but it does not work
function connectedNodes() {
//new parameters
linkDistance = 5;
fCharge = -10;
//restart simulation with new parameters
simulation.restart();
}
You need a reference to the forces you would like to update. This can be done using either of two ways:
As pointed out by Cool Blue in their comment, you can easily get a reference to the force by calling simulation.force() passing in just the name of the force it was registered with in the first place. If we had, supposedly, created our simulation while passing in an anonymous, in-place force like so:
var simulation = d3.forceSimulation()
.force("link", d3.forceLink() // "link" is the name to register the force
.id(function(d) { return d.id; })
.distance(linkDistance)
);
Later on the force can be obtained by its name whenever needed:
var forceLink = simulation.force("link"); // Get the force by its name
Personally, I like this approach and would prefer it over the second one, whenever possible, because I do not like having to many references / variables around.
Keep a reference to the force when creating it.
var forceLink = d3.forceLink() // Keep a reference to the force
.id(function(d) { return d.id; })
.distance(linkDistance);
var simulation = d3.forceSimulation()
.force("link", forceLink ) // Pass the reference when creating the simulation
No matter, which way you chose, you may then update your force by doing something like
linkDistance += 10;
forceLink.distance(linkDistance);
This will take the new value into account once the next tick is calculated. If the simulation has already come to a stop or you just want to heat it up again you may call
simulation.alpha(1).restart();
I have set up an example which shows these live updates when you hover over the SVG. This will update the linkDistance and restart the force layout.

D3 Transitionning data with sequences sunburst

Introducing
I'm using Sequences Sunburst of d3.js for visualization of data.
I want to add a transition between two datasets (triggered by a button). I would like each arc to animate to display the new data.
Something like this: (1)Sunburst_Exemple, but without changing the accessor.
Research
In the (1)Sunburst_Example, the value accessor is modified. But I want to change the data, not the function that defines how to reach the data.
So, I searched a way for redefining data into path.
I was inspired by (2)Sunburst_Exemple, using each() method to store old values and attrTween() for transitions. But nothing is changing and I have the following error message:
Maximum call stack size exceeded . Maybe caused by the fact I have a method and I'm not in a global scope.
(2) link : _http://ninjapixel.io/StackOverflow/doughnutTransition.html
Then I have tried (3)Zoomable_Sunburst example, but nothing it happens in my case... .
(3) link : _http://bl.ocks.org/mbostock/4348373
My Example
Here is my example : JSFIDDLE
Problem is :
colors are lost
transition is not happening
I think I don't understand how transitioning is really working, I could have missed something that could help me in this case.
Any help ?
-
Listener of button call click method that redefined nodes and path.
/*CHANGING DATA*/
function click(d){
d3.select("#container").selectAll("path").remove();
var nodes = partition.nodes(d)
.filter(function(d) {
return (d.dx > 0.005); // 0.005 radians = 0.29 degrees
}) ;
var path = vis.data([d]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", function(d) { return colors[d.name]; })
.style("opacity", 1)
.on("mouseover", mouseover)
.each(stash)
.transition()
.duration(750)
.attrTween("d", arcTween);
;
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
}
_
// Stash the old values for transition.
function stash(d) {
d.x0 = d.x;
d.dx0 = d.dx;
}
// Interpolate the arcs in data space.
function arcTween(a) {
var i = d3.interpolate({x: a.x0, dx: a.dx0}, a);
return function(t) {
var b = i(t);
a.x0 = b.x;
a.dx0 = b.dx;
return arc(b);
};
}
Data Characteristics :
the root node is the same for the two datasets.
the structure is globally the same, only the values are changing.
Some fields disappear but we can add them with value equal to 0.

Semantic zoom on map with circle showing capital

I wanted to implement semantic zoom on map of d3.js. I have developed a example of map and Major cities of particular country, which is working fine but sometime circle got overlap due to near places in maps so if i implement semantic zoom which will solve my circle overlapping problem.
I don't understand how to transform only graph not circle in my map.
My zooming function code is :
var zoom = d3.behavior.zoom()
.on("zoom",function() {
g.attr("transform","translate("+
d3.event.translate.join(",")+")scale("+d3.event.scale+")");
g.selectAll("circle")
.attr("d", path.projection(projection));
g.selectAll("path")
.attr("d", path.projection(projection));
});
My jsfiddle link
Anybody help me please!
Are you asking how to not scale the circles according to the zoom? The way you have it you are scaling the g element and the circles are in it. The way I'd do it is to "shrink" the circles when zoomed.
// zoom and pan
var zoom = d3.behavior.zoom()
.on("zoom",function() {
g.attr("transform","translate("+
d3.event.translate.join(",")+")scale("+d3.event.scale+")");
g.selectAll("circle")
.attr("r", function(){
var self = d3.select(this);
var r = 8 / d3.event.scale; // set radius according to scale
self.style("stroke-width", r < 4 ? (r < 2 ? 0.5 : 1) : 2); // scale stroke-width
return r;
});
});
Update fiddle.
I know this is an old post and it already has an accepted answer but as the original post suggests, d3's Semantic Zoom is a cleaner way of doing this. I implemented the same thing you did (circles on cities on a map) by following this demo https://bl.ocks.org/mbostock/368095. The only thing I had to change was I had to subtract the initial position of the circles in the transform function in order to correct their initial position.
function transform(t) {
return function(d) {
const point = [d.x, d.y] // this is the initial point
const tPoint = t.apply(point) // after translation
const finalPoint = [tPoint[0] - d.x, tPoint[1] - d.y]// subtract initial x & y to correct
return `translate(${finalPoint})`;
};
}

Resources