lucastimmons
lucastimmons

Reputation: 151

d3.js color from Json on data change

Using this as an example: http://mbostock.github.com/d3/talk/20111018/treemap.html

I am trying to make color of the rectangles in the tree map dependent on which data is visualized. The example lets you draw the tree map by size or by count. I've added two variables to each entry json file, "cola" and "colb". Each is just a color.

When the graphic is first drawn it is sorted based on size and uses cola to color the rectangles. I have no problem making the map redraw using count rather than size. What I can't figure out is how to get it to use colb instead of cola.

Here's part of the code. This is where the color is first picked.

  cell.append("svg:rect")
      .attr("width", function(d) { return d.dx - 1; })
      .attr("height", function(d) { return d.dy - 1; })
      .style("fill", function(d) { return d.cola; });

Here's the change function.

  d3.select("select").on("change", function() {
    treemap.value(this.value == "size" ? size : count).nodes(root);
    if (treemap.value(this.value == "size")) {
    cell.append("svg:rect").style("fill", function(d) {return d.cola; });
     }
    else {
     cell.append("svg:rect").style("fill", function(d) {return d.colb; });
    };
    zoom(node);

  });
});

Still trying to figure out d3.

Thanks

Upvotes: 0

Views: 3005

Answers (2)

nautat
nautat

Reputation: 5233

You could use some kind of variable in your code that specifies which color you want to use (based on the state of your select control):

var cola = (d3.select("select").node().value == "size");

and

cell.append("svg:rect")
    .attr("width", function(d) { return d.dx - 1; })
    .attr("height", function(d) { return d.dy - 1; })
    .style("fill", function(d) { return cola ? d.cola : d.colb; });

Then, the select button can toggle this variable:

d3.select("select").on("change", function() {
  treemap.value(this.value == "size" ? size : count).nodes(root);
  cola = (this.value == "size");
  zoom(node);
});

Make sure to update the fill style in your zoom function as well:

  t.select("rect")
      .attr("width", function(d) { return kx * d.dx - 1; })
      .attr("height", function(d) { return ky * d.dy - 1; })
      .style("fill", function(d) { return cola ? d.cola : d.colb; });

Upvotes: 2

musically_ut
musically_ut

Reputation: 34288

I think the problem is in the line:

 if (treemap.value(this.value == "size")) ...

It should read:

if (this.value == "size") ...

Also, you probably mean cell.selectAll('rect').style(...) instead of cell.append('rect').style(...) inside the if-then-else body. However, I cannot say for sure without seeing rest of the code.

Upvotes: 0

Related Questions