0

I am trying to come to grips with some D3 concepts but feel as though there are some fundamentals gaps in my knowledge. It seems to do with how the D3 stack() function works.

I am trying to understand why the following two code snippets are not equivalent. The first works and populates data, the second does not.

First (Working Code, Simplified):

var mainStack = d3.stack().keys(keys);
var seriesData = mainStack(dataset[0]);

gBars = g.selectAll("g")
         .data(seriesData, function (d, i) { return (i); })
         .enter().append("g").. more work here

Second (Not Working, Simplifed):

var mainStack = d3.stack().keys(keys);
var seriesData = mainStack(dataset[0]);

gBars = g.selectAll("g")
         .data(seriesData, function (d, i) { return (i); });

gBars.enter().append("g").. more work here

Basically, I have just tried to break up the code to make it simpler (for me) to read, and also to allow me to implement an exit() function. However, when i do the above, the graphs fail to display.

I thought that the gBar variables should maintain their previous selects?

Any assistance would be appreciated, I have successfully used this pattern for simple charts, hence my suspicion that this is related to something I am missing when the d3.stacked() function is involved which nests the data?

Sabur Aziz
  • 236
  • 1
  • 2
  • 9
  • You've left out some critical code in your question: how is `gBars` used after your `...`? What's the `more work here`? That's the important part! – Mark Jan 21 '17 at 15:38
  • Hi, its simply adding a few attributes to the select items. eg: .apprend("g").attr("fill","#ff0000") <-- I left it out since I wasnt doing anythign special. gBars isnt used after this, I'm just using it this way "learn" and play around with a few things. – Sabur Aziz Jan 21 '17 at 21:39

1 Answers1

0

With some friendly help, I found that the difference is in the way v4 handles selects. The answer was to utilise merges to combine the various selects and then perform any combined updates on the merged nodes.

Eg:

var mainStack = d3.stack().keys(keys);
var seriesData = mainStack(dataset[0]);

var gBarsUpdate = g.selectAll("g")
     .data(seriesData, function (d, i) { return (i); });

var gBarsEnter = gBarsUpdate.enter().append("g")

var gBars = gBarsEnter.merge(gBarsUpdate)

//now update combined with common attributes as required
gBars.attr("fill", "#ff0000"); //etc

Hope this helps anyone else a bit confused by this. Took me a bit of time to understand what was going on, but thanks to some smart people, they put me on the right track :-)

ps. My problem ended up having nothing to do with the stack() function.

Sabur Aziz
  • 236
  • 1
  • 2
  • 9