javascript - D3.js - 来自平面 JSON 层次结构的 TreeMap

标签 javascript json d3.js treemap

我正在尝试在 d3.js 中渲染树状图并使用示例代码 - http://mbostock.github.com/d3/ex/treemap.html :

enter image description here

我遇到了一个问题,因为我的源 JSON 是一个扁平的 heirachy,因此对 treemap.nodes 的调用是错误的。

谁能建议如何返回扁平层次结构?

我的示例 JSON:

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

到目前为止我的完整代码:

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
     }
  }

});

感谢任何评论。

最佳答案

不确定你的意思是平坦的。如果您的意思是 D3 中没有“节点”父类(super class)别,那么您可以使用:

.data(treemap)

代替:

.data(treemap.nodes)

但如果您的 JSON 中没有“children”属性,您将无法获得任何分层打包。

关于javascript - D3.js - 来自平面 JSON 层次结构的 TreeMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10261322/

相关文章:

javascript - 为什么旋转元件会弹跳?

javascript - 调用 fetch() 时,主干集合给出 "Ajax of undefined"错误

javascript - 如何将大数组切成固定长度的小块

java - 如何使用嵌套的 json 数组反序列化 json 对象

javascript - 从 JS 函数调用 React Component 函数

javascript - D3.js 获取面积图最近的 X 和 Y 坐标

javascript - 从 html 字符串中删除 div 及其内容

javascript - jquery 样式在 react 组件中不起作用

android - 错误 org.json.JSONException : Index 2 out of range

java - 如何使用 Jackson 解析对象数组?