Update Selection in D3 is empty - d3.js

In my code, my update selection is always empty, as is my exit selection, so the transitions never run. Every time I refresh, I end up redrawing the entire DOM fragment as if it never existed before (i.e. I can remove everything but .enter and the behavior doesn't change).
I'm making use of a key function in data() to ensure the join is being made on a unique value instead of by position.
The entire code is at http://jsfiddle.net/colin_young/xRQjX/23/, but I've extracted what I think is the relevant section here (basically, I'm just trying to follow the General Update Pattern):
var key = function (d) {
return d.index;
}
var filterDistance = function () {
var names = list.selectAll("div")
.data(byDistance.bottom(40), key);
// Update
names.attr("class", "update");
// Add
names.enter()
.append("div")
.attr("class", "enter")
.style("opacity", "0")
.transition()
.duration(500)
.style("opacity", "1")
.text(function (d) {
return displayText(d);
});
// Remove
names.exit()
.transition()
.duration(750)
.style("opacity", "0")
.remove();
};

bewest at https://groups.google.com/forum/?fromgroups=#!topic/d3-js/9mrspdWqkiU was able to find the problem. It turned out that in my "working" summary display, I was using $('results').text('insert summary here') which of course wipes out anything else that I might have stuck in there (like my D3 generated divs for instance).

Related

How to add label or custom value on Mapchart's path using geoChoroplethChart and dc.js?

var IndChart = dc.geoChoroplethChart("#india-chart");
var states = data.dimension(function (d) {
return d["state_name"];
});
var stateRaisedSum = states.group().reduceSum(function (d) {
return d["popolation"];
});
IndChart
.width(700)
.height(500)
.dimension(states)
.group(stateRaisedSum)
.colors(d3.scale.ordinal().domain().range(["#27AE60", "#F1C40F", "#F39C12","#CB4335"]))
.overlayGeoJson(statesJson.features, "state", function (d) { //console.log(d.properties.name);
return d.id;
})
.projection(d3.geo.mercator().center([95, 22]).scale(940))
.renderLabel(true)
.title(function (d) { console.log(d); return d.key + " : " + d.value ;
})
.label(function (d) { console.log(d);}) ;
wanted to add Label or custom value(25%, added in Map chart screen-shots) in map chart for each path using dc.js.
In the comments above, you found or created a working example that answers your original question. Then you asked how to make it work for two charts on the same page.
This is just a matter of getting the selectors right, and also understanding how dc.js renders and redraws work.
First off, that example does
var labelG = d3.select("svg")
which will always select the first svg element on the page. You could fix this by making the selector more specific, i.e. #us-chart svg and #us-chart2 svg, but I prefer to use the chart.select() function, which selects within the DOM tree of the specific chart.
Next, it's important to remember that when you render a chart, it will remove everything and start from scratch. This example calls dc.renderAll() twice, so any modifications made to the first chart will be lost on the second render.
In contrast, a redraw happens when any filter is changed, and it incrementally changes the chart, keeping the previous content.
I prefer to listen to dc.js chart events and make my modifications then. That way, every time the chart is rendered or redrawn, modifications can be made.
In particular, I try to use the pretransition event whenever possible for modifying charts. This happens right after drawing, so you have a chance to change things without any glitches or pauses.
Always add event listeners before rendering the chart.
Adding (the same) handler for both charts and then rendering, looks like this:
usChart.on('pretransition', function(chart) {
var project = d3.geo.albersUsa();
var labelG = chart.select("svg")
.selectAll('g.Title')
.data([0])
.enter()
.append("svg:g")
.attr("id", "labelG")
.attr("class", "Title");
labelG.selectAll("text")
.data(labels.features)
.enter().append("svg:text")
.text(function(d){return d.properties.name;})
.attr("x", function(d){return project(d.geometry.coordinates)[0];})
.attr("y", function(d){return project(d.geometry.coordinates)[1];})
.attr("dx", "-1em");
});
usChart2.on('pretransition', function(chart) {
var project = d3.geo.albersUsa();
var labelG = chart.select("svg")
.selectAll('g.Title')
.data([0])
.enter()
.append("svg:g")
.attr("id", "labelG")
.attr("class", "Title");
labelG.selectAll("text")
.data(labels.features)
.enter().append("svg:text")
.text(function(d){return d.properties.name;})
.attr("x", function(d){return project(d.geometry.coordinates)[0];})
.attr("y", function(d){return project(d.geometry.coordinates)[1];})
.attr("dx", "-1em");
});
dc.renderAll();
I used one more trick there: since pretransition happens for both renders and redraws, but we only want to add these labels once, I use this pattern:
.selectAll('g.Title')
.data([0])
.enter()
.append("svg:g")
.attr("class", "Title");
This is the simplest data binding there is: it says we want one g.Title and its data is just the value 0. Since we give the g element the Title class, this ensures that we'll add this element just once.
Finally, the result of this expression is an enter selection, so we will only add text elements when the Title layer is new.
Fork of your fiddle.

How do I dynamically update displayed elements in D3

I have a function that loads an initial array of points onto a map using D3:
var fires = []; //huge array of objects
function update(selection) {
feature = g.selectAll("path")
.data(selection);
feature.attr("class", "update");
feature.enter().append("path")
.attr("class", "enter")
.style("fill", function(d) {return colorScale(d.area)});
feature.exit().remove();
}
I call it initially with a large array:
update(fires);
I also have a histogram that allows me to narrow down the selection based on years. Using a D3 brush, on 'brushend' I call a function called brushed:
function brushed() {
if (!d3.event.sourceEvent) return; // only transition after input
var extent0 = brush.extent();
startYear = Math.floor(extent0[0]);
endYear = Math.floor(extent0[1]);
var selectedFires = fires.filter(function(fire) {
if(fire.year >= startYear && fire.year <= endYear) return fire;
});
console.log(selectedFires.length); //does reflect the proper amount of elements
update(selectedFires);
}
When I narrow the selection, the points on the map disappear as expected. When I widen it, the points/elements do not return. The array is getting the correct elements in it, they're just not being appended to the SVG.
I'm missing something fundamental as the examples I've seen: http://bl.ocks.org/mbostock/3808218 appear to append elements just fine.
Without seeing the rest of the code (which really helps), and focusing on your selection piece alone, try this:
function update(selection) {
// binding the data
feature = g.selectAll(".path")
.data(selection);
// exit selection
feature
.exit()
.remove();
// enter selection
feature
.enter()
.append("path")
.attr("class","path");
// update selection
feature
.style("fill", function(d) {return colorScale(d.area)});
// update selection
feature
.style("fill", function(d) {return colorScale(d.area)})
.attr("d",path); // this was the missing piece!
}
NOTE: you also want to comment out where you hardcoded the extent of the brush:
//brush
var brush = d3.svg.brush()
.x(areaYearScale)
//.extent([1984, 2013]) // comment this out
.on("brushend", brushed);

d3 Line Chart with enter-update-exit logic

today I created a simple Bar Chart with the enter-update-exit logic - everything works fine. Now I will do the same with a line chart - the whole dataset for the chart can change at any time, so I will update the chart smoothly. I can't find a good example with a line chart and the enter-update-exit logic (or I'm looking wrong). Currently I have to remember that if the chart is called for the first time or the data to be updated (data has changed) - This is my dirty version:
var channelGroup = d3.select(".ch1");
// init. Line Chart
if (firstLoad) {
channelGroup
.append('path')
.attr("class", "line")
.style("stroke", channel.Color)
.transition()
.ease("linear")
.duration(animChart / 2)
.attr('d', line(channel.DataRows));
}
// update Line Chart
else {
channelGroup
.selectAll("path")
.data([channel.DataRows])
.transition()
.ease("linear")
.duration(animChart / 2)
.attr("d", function (d) { return line(d); });
}
how can I realize this in a good manner?... thx!
You're mixing up two different approaches, one binding data to the line and the other just passing the data to the line function. Either one could work (so long as you only have the one line), but if you want to get rid of your if/else construct you're still going to need to separate the statements handling entering/appending the element from the statements updating it.
Option 1 (don't bind data, just call the function):
var linegraph = channelGroup.select('path');
if ( linegraph.empty() ) {
//handle the entering data
linegraph = channelGroup.append('path')
.attr("class", "line")
.style("stroke", channel.Color);
}
linegraph
.transition()
.ease("linear")
.duration(animChart / 2)
.attr('d', line(channel.DataRows));
Option 2 (use a data join):
var linegraph = channelGroup.selectAll("path")
.data([channel.DataRows]);
linegraph.enter().append('path')
.attr("class", "line");
linegraph
.transition()
.ease("linear")
.duration(animChart / 2)
.attr("d", line); //This is slightly more efficient than
//function (d) { return line(d); }
//and does the exact same thing.
//d3 sees that `line` is a function, and
//therefore calls it with the data as the
//first parameter.

D3 Data updates not working correctly

I thought I understood the D3 enter/update/exit, but I'm having issues implementing an example. The code in http://jsfiddle.net/eamonnmag/47TtN/ illustrates what I'm doing. As you'll see, at each 5 second interval, I increase the rating of an item, and update the display again. This works, in some way. The issue is in only updating what has changed - D3 is updating everything in this case. The enter and exit methods, displayed in the console output that nothing has changed, which makes my think that it's treating each array as a completely new instance.
My understanding of the selectAll() and data() calls was that it would 'bind' all data to a map called 'chocolates' somewhere behind the scenes, then do some logic to detect what was different.
var chocolate = svg.selectAll("chocolates").data(data);
In this case, that is not what's happening. This is the update code. Any pointers to what I've missed are most appreciated!
function update(data){
var chocolate = svg.selectAll("chocolates").data(data);
var chocolateEnter = chocolate.enter().append("g").attr("class", "node");
chocolateEnter.append("circle")
.attr("r", 5)
.attr("class","dot")
.attr("cx", function(d) {return x(d.price)})
.attr("cy", function(d) {
//put the item off screen, to the bottom. The data item will slide up.
return height+100;})
.style("fill", function(d){ return colors(d.manufacturer); });
chocolateEnter
.append("text")
.text(function(d) {
return d.name;})
.attr("x", function(d) {return x(d.price) -10})
.attr("y", function(d){return y(d.rating+step)-10});
chocolateEnter.on("mouseover", function(d) {
d3.select(this).style("opacity", 1);
}).on("mouseout", function(d) {
d3.select(this).style("opacity", .7);
})
chocolate.selectAll('circle')
.transition().duration(500)
.attr('cy', function(d) {return y(d.rating+step)});
var chocolateExit = chocolate.exit().remove();
chocolateExit.selectAll('circle')
.attr('r', 0);
}
setInterval(function() {
chocolates[3].rating = Math.min(chocolates[3].rating+1, 5);
update(chocolates);
}, 5000);
Easy as apple pie!
Why are you doing svg.selectAll("chocolates")? There is no HTML element in your DOM called chocolates.
You need to change that to svg.selectAll(".node"). That will fix the problem.
There are a couple of issues in your code. First, the logic to detect what's different is, by default, to use the index of the item. That is, the first data item is matched to the first DOM element, and so on. This works in your case, but will break if you ever pass in partial data. I would suggest using the second argument to .data() to tell it how to match:
var chocolate = svg.selectAll("g.node").data(data, function(d) { return d.name; });
Second, as the other poster has pointed out, selecting "chocolate" will select nothing, as there are no such DOM elements. Just select the actual elements instead.
Finally, since you're adding g elements for the data items, you might as well use them. What I mean is that currently, you're treating the circles and text separately and have to update both of them. You can however just put everything underneath g elements. Then you have to update only those, which simplifies your code.
I've made all the above changes in your modified fiddle here.

d3: How to properly chain transitions on different selections

I am using V3 of the popular d3 library and basically want to have three transitions, followed by each other: The first transition should apply to the exit selection, the second to the update selection and the third to the enter selection. They should be chained in such a manner that when one of the selections is empty, its respective transition is skipped. I.e. when there is no exit selection, the update selection should start immediately. So far, I have come up with this code (using the delay function).
// DATA JOIN
var items = d3.select('#data').selectAll('.item');
items = items.data(data, function(d){
return d.twitter_screenname;
});
// EXIT
items.exit().transition().duration(TRANSITION_DURATION).style('opacity', 0).remove();
// UPDATE
// Divs bewegen
items.transition().duration(TRANSITION_DURATION).delay(TRANSITION_DURATION * 1)
.style('left', function(d, i) {
return positions[i].left + "px";
}).style('top', function(d, i) {
return positions[i].top + "px";
});
// ENTER
// Divs hinzufügen
var div = items.enter().append('div')
.attr('class', 'item')
.style('left', function(d, i) {
return positions[i].left + "px";
}).style('top', function(d, i) {
return positions[i].top + "px";
});
div.style('opacity', 0)
.transition().duration(TRANSITION_DURATION).delay(TRANSITION_DURATION * 2)
.style('opacity', 1);
First of all it doesn't allow to "skip" transitions and secondly I think there is a better way than delay. I've looked at http://bl.ocks.org/mbostock/3903818 but I did not really understand what is happening.
Also, somehow just writing items.exit().transition().duration(TRANSITION_DURATION).remove() does not work with the items, probably because they are not SVG elements but divs.
Sure. Here are two ways.
First, you could use an explicit delay, which you then compute using selection.empty to skip empty transitions. (This is only a minor modification of what you have already.)
var div = d3.select("body").selectAll("div")
.data(["enter", "update"], function(d) { return d || this.textContent; });
// 2. update
div.transition()
.duration(duration)
.delay(!div.exit().empty() * duration)
.style("background", "orange");
// 3. enter
div.enter().append("div")
.text(function(d) { return d; })
.style("opacity", 0)
.transition()
.duration(duration)
.delay((!div.exit().empty() + !div.enter().empty()) * duration)
.style("background", "green")
.style("opacity", 1);
// 1. exit
div.exit()
.style("background", "red")
.transition()
.duration(duration)
.style("opacity", 0)
.remove();
http://bl.ocks.org/mbostock/5779682
One tricky thing here is that you have to create the transition on the updating elements before you create the transition on the entering elements; that’s because enter.append merges entering elements into the update selection, and you want to keep them separate; see the Update-only Transition example for details.
Alternatively, you could use transition.transition to chain transitions, and transition.each to apply these chained transitions to existing selections. Within the context of transition.each, selection.transition inherits the existing transition rather than creating a new one.
var div = d3.select("body").selectAll("div")
.data(["enter", "update"], function(d) { return d || this.textContent; });
// 1. exit
var exitTransition = d3.transition().duration(750).each(function() {
div.exit()
.style("background", "red")
.transition()
.style("opacity", 0)
.remove();
});
// 2. update
var updateTransition = exitTransition.transition().each(function() {
div.transition()
.style("background", "orange");
});
// 3. enter
var enterTransition = updateTransition.transition().each(function() {
div.enter().append("div")
.text(function(d) { return d; })
.style("opacity", 0)
.transition()
.style("background", "green")
.style("opacity", 1);
});
http://bl.ocks.org/mbostock/5779690
I suppose the latter is a bit more idiomatic, although using transition.each to apply transitions to selections (rather than derive transitions with default parameters) isn’t a widely-known feature.

Resources