user1866670
user1866670

Reputation: 33

d3.js -- stacked bar with color categories

I'm trying to build a stacked bar chart using the stack layout in d3.js (see where I'm at here: http://bl.ocks.org/4676028). I've got the bars displaying and stacking correctly. But there are gaps in my data, so for those instances I'm using interpolated values. So in my data file, I have two columns for each category of data: one for the actual number values, and one with a 0/1 flag indicating if the value is an interpolation or not.

What I want to do is check the flag and if the value is interpolated, to alter the color or opacity of the rectangle fill. But I cannot for the life of me figure out how to do this -- d3's data structures have me pretty flummoxed. Any help would be most appreciated. Thanks!

Upvotes: 1

Views: 1156

Answers (1)

user1866670
user1866670

Reputation: 33

Figured this out finally; posting in case anyone else runs into a similar issue. You can access a different array using standard javascript syntax. The only tricky thing is that with d3's stack layout, the index value (i) is reset for each series within the stack. So you need some sort of counter value that tracks this an increments each time a new series is started.

var n = 0;
var rect = tnum.selectAll("rect")
  .data(function(d) {return(d)})
.enter().append("svg:rect")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return -y(d.y0) - y(d.y); })

  .attr("height", function(d) { return y(d.y); })
  .attr("width", x.rangeBand())
  .attr("title",  function(d) { return d.x; }) 
  .attr("class", function(d) { return d.y; })
  .style("opacity", function(d, i) { 


    if(i === interp[0].length-1 && n < 2) {
    n+=1;
    }
    var flag = interp[n][i].int;

  console.log();

  if (flag == 1) {return "0.85"}    // if close is less than 400 fill = red
        else    { return "1" ;}})

Upvotes: 1

Related Questions