d3.js transition end event - d3.js

I am applying a transition to a group of nodes returned by selectAll(). I thought the end event would fire after all transitions finished, but each("end",function) gets called at the end of each transition.
So is there any way to set a callback that will be called after transitions on all selected node finishes ?
Should I use call for this? but I don't see it used as end callback anywhere in documentation.
also I can run a counter inside each callback. but is there any way to know how many nodes are still pending to finish transition ? or index of current node in group of selected nodes ?
I've two select() calls in chain like selectAll('.partition').selectAll('.subpartition')
so index argument passed to each callback will rotated n times.

As far as I know there is not a built in way to know when the last transition of a group has finished but there are ways around it. One way that I have used several times involves maintaining a count of transitions that have finished.
var n = 0;
d3.selectAll('div')
.each(function() { // I believe you could do this with .on('start', cb) but I haven't tested it
n++;
})
.transition()
.on('end', function() { // use to be .each('end', function(){})
n--;
if (!n) {
endall();
}
})
function endall() {
// your end function here
}
Here are the links to the relevant documentation:
https://github.com/d3/d3-transition#control-flow
https://github.com/d3/d3-transition#the-life-of-a-transition

Here's a clean way to accomplish what you want:
function endAll (transition, callback) {
var n;
if (transition.empty()) {
callback();
}
else {
n = transition.size();
transition.each("end", function () {
n--;
if (n === 0) {
callback();
}
});
}
}
You can then easily call this function like so:
selection.transition()
.call(endAll, function () {
console.log("All the transitions have ended!");
});
This will work even if the transition is empty.

I had the same issue
that the call back gets executed with each element
I have solved that using underscore once method
http://underscorejs.org/#once
d3.select("#myid")
.transition()
.style("opacity","0")
.each("end", _.once(myCallback) );

Related

dc.js Grouping for Bubble Chart Removing from wrong groups

I'm trying to create a bubble chart with dc.js that will have a bubble for each data row and will be filtered by other charts on the same page. The initial bubble chart is created correctly, but when items are filtered from another chart and added or removed from the group it looks like they are being applied to the wrong group. I'm not sure what I'm messing up on the grouping or dimensions. I've created an example fiddle here
There's simple pie chart to filter on filterColumn, a bubble chart that uses identifer1, a unique field, as the dimension and xVal, yVal, and rVal to display the data, and a dataTable to display the current records.
I've tried other custom groups functions, but switched to the example from the FAQ and still had problems.
var
filterPieChart=dc.pieChart("#filterPieChart"),
bubbleChart = dc.bubbleChart('#bubbleChart'),
dataTable = dc.dataTable('#data-table');
var
bubbleChartDim=ndx.dimension(dc.pluck("identifier1")),
filterPieChartDim=ndx.dimension(dc.pluck("filterColumn")),
allDim = ndx.dimension(function(d) {return d;});
var filterPieChartGroup=filterPieChartDim.group().reduceCount();
function reduceFieldsAdd(fields) {
return function(p, v) {
fields.forEach(function(f) {
p[f] += 1*v[f];
});
return p;
};
}
function reduceFieldsRemove(fields) {
return function(p, v) {
fields.forEach(function(f) {
p[f] -= 1*v[f];
});
return p;
};
}
function reduceFieldsInitial(fields) {
return function() {
var ret = {};
fields.forEach(function(f) {
ret[f] = 0;
});
return ret;
};
}
var fieldsToReduce=['xVal', 'yVal', 'rVal'];
var bubbleChartGroup = bubbleChartDim.group().reduce(
reduceFieldsAdd(fieldsToReduce),
reduceFieldsRemove(fieldsToReduce),
reduceFieldsInitial(fieldsToReduce)
);
filterPieChart
.dimension(filterPieChartDim)
.group(filterPieChartGroup)
...
;
bubbleChart
.dimension(bubbleChartDim)
.group(bubbleChartGroup)
.keyAccessor(function (p) { return p.value.xVal; })
.valueAccessor(function (p) { return p.value.yVal; })
.radiusValueAccessor(function (p) { return p.value.rVal; })
...
;
This was a frustrating one to debug. Your groups and reductions are fine, and that's the best way to plot one bubble for each row, using a unique identifier like that.
[It's annoying that you have to specify a complicated reduction, when the values will be either the original value or 0, but the alternatives aren't much better.]
The reductions are going crazy. Definitely not just original values and zero, some are going to other values, bigger or negative, and sometimes clicking a pie slice twice does not even return to the original state.
I put breakpoints in the reduce functions and noticed, as you did, that the values were being removed from the wrong groups. How could this be? Finally, by logging bubbleChartGroup.all() in a filtered handler for the pie chart, I noticed that the groups were out of order after the first rendering!
Your code is fine. But you've unearthed a new bug in dc.js, which I filed here.
In order to implement the sortBubbleSize feature, we sort the bubbles. Unfortunately we are also sorting crossfilter's internal array of groups, which it trusted us with. (group.all() returns an internal data structure which must never be modified.)
The fix will be easy; we just need to copy the array before sorting it. You can test it out in your code by commenting out sortBubbleSize and instead supplying the data function, which is what it does internally:
bubbleChart.data(function (group) {
var data = group.all().slice(0);
if (true) { // (_sortBubbleSize) {
// sort descending so smaller bubbles are on top
var radiusAccessor = bubbleChart.radiusValueAccessor();
data.sort(function (a, b) { return d3.descending(radiusAccessor(a), radiusAccessor(b)); });
}
return data;
});
Notice the .slice(0) at the top.
Hope to fix this in the next release, but this workaround is pretty solid in case it takes longer.
Here is a fiddle demonstrating the workaround.

D3 - using enter() and exit() selections to update child elements

I have g.row elements containing g.cell elements, each containing a rect element. My nested data is bound to g.row and then g.cell. The rect elements access the data bound to g.cell.
At the moment my enter and exit selections add and remove g.cell. It would be more efficient to have them add and remove the rect elements, because g.cell has events bound to it that I need to reassign. But is this possible? I can't see how to get it to work.
I've managed to run cell.exit().selectAll("rect").remove(); which works fine. But cell.enter().selectAll("g.cell").append("rect"); throws an error ("[this code] is not a function"). While cell.enter().append("rect") doesn't append a rect.
Current code on g.cell:
var cell = row.selectAll("g.cell")
.data(function(d){
return d.value.filter(function(p){
if (p[1]=='') {
return horizNodesCopy.indexOf(p[0])!=-1;
} else {
return horizNodesCopy.indexOf(p[0]+' -- '+p[1])!=-1;
}
});
});
var cell2 = cell.enter().append("g")
.attr("class",function(d,i,j){ return "cell cell_"+i; })
.attr('transform',function(d,i,j){
if (d[1]=='') {
return 'translate('+ x(d[0]) +',0)';
} else {
return 'translate('+ x(d[0]+' -- '+d[1]) +',0)';
}
});
addRectangles(cell2,colorScale);
cell.exit().remove();
This feels like it's going to be something obvious :/

dc.js exclude the brushed area and highlight rest

I'm not data-viz expert or d3, I have found plenty of examples to how to build brushing and zoom for example Mike.
They all have shown how to filter to the brushed area but I want to achieve to reverse of that effect, how?
Can someone through me ideas how to achieve it?
I don't know why I assumed you meant a bar chart when you linked to an area chart. You can ignore the highlighting section and skip to filtering if you're interested in doing this with line charts. There is no highlighting of line chart, just the brush itself.
Highlighting the bars in reverse
This isn't all that hard, but it's somewhat messy because we replace an undocumented function in the chart. Like most things in dc.js, if there isn't an option, you can usually replace the functionality (or add or change stuff once the chart has rendered/drawn).
Here there's a specific, public function which fades the deselected areas. It's called fadeDeselectedArea. (Actually it both fades and un-fades when the chart is ordinal, but we'll ignore that part.)
The original function looks like this:
_chart.fadeDeselectedArea = function () {
var bars = _chart.chartBodyG().selectAll('rect.bar');
var extent = _chart.brush().extent();
if (_chart.isOrdinal()) {
if (_chart.hasFilter()) {
bars.classed(dc.constants.SELECTED_CLASS, function (d) {
return _chart.hasFilter(d.x);
});
bars.classed(dc.constants.DESELECTED_CLASS, function (d) {
return !_chart.hasFilter(d.x);
});
} else {
bars.classed(dc.constants.SELECTED_CLASS, false);
bars.classed(dc.constants.DESELECTED_CLASS, false);
}
} else {
if (!_chart.brushIsEmpty(extent)) {
var start = extent[0];
var end = extent[1];
bars.classed(dc.constants.DESELECTED_CLASS, function (d) {
return d.x < start || d.x >= end;
});
} else {
bars.classed(dc.constants.DESELECTED_CLASS, false);
}
}
};
source link
We'll ignore the ordinal part because that's only individual selection, not brushed selection. Here is the reverse of the second part:
spendHistChart.fadeDeselectedArea = function () {
var _chart = this;
var bars = _chart.chartBodyG().selectAll('rect.bar');
var extent = _chart.brush().extent();
// only covering the non-ordinal (ranged brush) case here...
if (!_chart.brushIsEmpty(extent)) {
var start = extent[0];
var end = extent[1];
bars.classed(dc.constants.DESELECTED_CLASS, function (d) {
return d.x >= start && d.x < end;
});
} else {
bars.classed(dc.constants.DESELECTED_CLASS, false);
}
};
Creating a variable _chart is just to keep the code the same as much as possible. You can see that d.x >= start && d.x < end is exactly the opposite of d.x < start || d.x >= end
Reversing the filtering
We'll need to add a filterHandler to the chart in order to reverse the filtering. Again, we'll base it off the default behavior, but here there's a legitimate customization point so we don't have to replace a function, just supply one:
spendHistChart.filterHandler(function(dimension, filters) {
if(filters.length === 0)
dimension.filter(null);
else {
// assume one RangedFilter but apply in reverse
// this is less efficient than filterRange but it shouldn't
// matter much unless the data is huge
var filter = filters[0];
dimension.filterFunction(function(d) {
return !filter.isFiltered(d);
})
}
});
Again, we cut out the cases we don't care about. There is no reason to be general about something that has a specific purpose and it will only cause maintenance problems. The only two cases we care about are no filter and one range filter.
Here the RangedFilter already supplies a filter function, so we can just call it and not (!) the result. This will be slightly less efficient than the filterRange but crossfilter has no native support for multiple ranges (or the inverse of a range).
That's it! Fiddle here: http://jsfiddle.net/gordonwoodhull/46snsbc2/8/

Using Custom reduce function with Fake Groups

I have line chart where I need to show frequency of order executions over the course of a day. These orders are grouped by time interval, for example every hour, using custom reduce functions. There could be an hour interval when there were no order executions, but I need to show that as a zero point on the line. I create a 'fake group' containing all the bins with a zero count...and the initial load of the page is correct.
However the line chart is one of 11 charts on the page, and needs to be updated when filters are applied to other charts. When I filter on another chart, the effects on this particular frequency line chart are incorrect. The dimension and the 'fake group' are used for the dc.chart.
I put console.log messages in the reduceRemove function and can see that there is something wrong...but not sure why.
Any thoughts on where I could be going wrong.
FrequencyVsTimeDimension = crossfilterData.dimension(function (d) { return d.execution_datetime; });
FrequencyVsTimeGroup = FrequencyVsTimeDimension.group(n_seconds_interval(interval));
FrequencyVsTimeGroup.reduce(
function (p, d) { //reduceAdd
if (d.execution_datetime in p.order_list) {
p.order_list[d.execution_datetime] += 1;
}
else {
p.order_list[d.execution_datetime] = 1;
if (d.execution_type !== FILL) p.order_count++;
}
return p;
},
function (p, d) { //reduceRemove
if (d.execution_type !== FILL) p.order_count--;
p.order_list[d.execution_datetime]--;
if (p.order_list[d.execution_datetime] === 0) {
delete p.order_list[d.execution_datetime];
}
return p;
},
function () { //reduceInitial
return { order_list: {}, order_count: 0 };
}
);
var FrequencyVsTimeFakeGroup = ensure_group_bins(FrequencyVsTimeGroup, interval); // function that returns bins for all the intervals, even those without data.

Waypoint unrecognized on Ajax-loaded content

I'm loading a page into a div. I'm also attempting to establish a waypoint, so that when the user scrolls down the page, the menu will change colors.
The problem I am having is the new height of the div is not recognized by the browser once the ajax content is loaded.
Here's what I have:
$(".cta").live('click', function () {
$('#faq').load('about-us/faqs/index.html'),
function () {
$("#faq").waypoint(function (event, direction) {
if (direction === 'up') {
$("#siteNav li a").removeClass("siteNavSelected");
$("#siteNav li.nav3 a").addClass("siteNavSelected");
}
}, {
offset: function () {
return $.waypoints('viewportHeight') - $("#faq").outerHeight();
}
});
}
return false;
});
Any ideas? Thanks.
Use $.waypoints('refresh');, from the documentation:
This will force a recalculation of each waypoint’s trigger point based on its offset option. This is called automatically whenever the window is resized or new waypoints are added. If your project is changing the DOM or page layout without doing one of these things, you may want to manually call it.
I'm not familiar with the intrinsics of the waypoint plugin, but you could also bind a scroll event and then capture the .scrollTop() value. Would look something like this:
$(document).bind('scroll', function(event) {
var scrollTop = $(window).scrollTop();
if (scrollTop < 1000 && $('siteNav li').hasClass('styleA')) { return; }
else {
$('siteNav li').removeClass('styleB');
$('siteNav li').addClass('styleA');
}
if (scrollTop > 1000 && $('siteNav li').hasClass('styleB')) { return; }
else {
$('siteNav li').removeClass('styleA');
$('siteNav li').addClass('styleB');
}
});
You have to play with the values a little to get it acting at the right spot. Also you have to use a greater or less than value in the test as if a user is at the top of the page and uses the scroll-wheel on his mouse to fly down the page, you don't get every value in between.

Resources