Ben
Ben

Reputation: 6086

D3.js - treemap from flat JSON hierarchy

I am trying to render a treemap in d3.js and using the example code - http://mbostock.github.com/d3/ex/treemap.html:

enter image description here

I am encountering an issue in that my source JSON is a flat heirachy, and therefore the call to treemap.nodes is wrong.

Can anyone advise how to return a flat hierarchy?

My sample JSON:

[
    {"ticker":"$GOOG","count":"82","sentiment":"9"},
    {"ticker":"$AAPL","count":"408","sentiment":"8"}, ...

And my full code so far:

d3.json("/finance/data", function(json) {   

    var w = 960,
      h = 500,
      color = d3.interpolateRgb("rgb(0,255,0)", "rgb(255,0,0)");
      //xcolor = d3.scale.linear().domain([-26,13]).range("rgb(0,255,0)", "rgb(255,0,0)"),
      x = d3.scale.linear().domain([-26,13]).range([0, 1]),
      stepsize = [2.46, 1.66],
      minval = [-16.28, -16.67];


   var treemap = d3.layout.treemap()
      .size([w, h])
      .sticky(true)
      .value(function(d) { return d.count; });

   var div = d3.select("#treemap-transition").append("div")
      .style("position", "relative")
      .style("width", w + "px")
      .style("height", h + "px");


  div.data([json]).selectAll("div")
     .data(treemap.nodes)
    .enter().append("div")
      .attr("class", "cell")
      .style("background", function(d) { return treemap_color(d.sentiment, 2.5, 10); }) 
      .call(cell)
      .attr("text-anchor", "middle")
      .text(function(d) { return d.children ? null : d.ticker; });


  function cell() {
    this
      .style("left", function(d) { return d.x + "px"; })
      .style("top", function(d) { return d.y + "px"; })
      .style("width", function(d) { return d.dx - 1 + "px"; })
      .style("height", function(d) { return d.dy - 1 + "px"; })
      .style("text-anchor", "middle");
  }


  function treemap_color(value, stepsize, steps) {
     if (value == 0) {

        return "rgb(0,0,0)";

     } else if (value < 0 ) {

        var x = Math.round( (255/steps) * Math.abs( value/stepsize) );
        return 'rgb(0,' + x + ',0)';   //DECREASE in unemployment => green

     } else {

        var y = Math.round(  (255/steps) * value/stepsize );
        return 'rgb(' + y + ',0,0)';  //INCREASE in unemployment => red
     }
  }

});

Appreciate any comments.

Upvotes: 1

Views: 6144

Answers (1)

Elijah
Elijah

Reputation: 4639

Not sure how you mean flat. If you mean you don't have a "Nodes" supercategory in D3, then you can just use:

.data(treemap)

instead of:

.data(treemap.nodes)

but without the "children" attribute in your JSON, you won't get any hierarchical packing.

Upvotes: 2

Related Questions