nola_jun 于 2016.09.06 21:09 提问

d3jstree图例展示出错，跪求大神指点
``````<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var diameter = 960;
/*定义一个Tree对象,定义旋转角度和最大半径*/
var tree = d3.layout.tree().size([360, diameter / 2 - 120]).separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
/*定义布局方向*/
var diagonal = d3.svg.diagonal.radial().projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
/*新建画布，移动到圆心位置*/
var svg = d3.select("body").append("svg").attr("width", diameter).attr("height", diameter - 150).append("g").attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");

d3.json("test2.json", function(error, root) {
if (error) throw error;
/*根据数据生成nodes集合，获取node集合的关系集合*/
var nodes = tree.nodes(root),

if(d.type == 1){/*当前企业*/
d.level = "#24a6da";
}else if(d.type == 2){/*股东*/
d.level = "#4cd1e0";
}else if(d.type == 3){/*对外投资*/
d.level = "#92db8c";
}
return d.level});

var node = svg.selectAll(".node").data(nodes).enter().append("g").attr("class", "node").attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })

/*为节点添加圆形标记,如果有子节点为蓝色，否则白色*/
node.append("circle").attr("r", 6.5).style("fill", function(d) { return d.level; });
``````

/*图例的位置大小*/
var color_block = level_groups.data('links').append('rect').attr("x", diameter/2 - 60).attr("width",20).attr("height",20).attr("fill",function(d){
if(d.type == 1){/*当前企业*/
d.level = "#24a6da";return d.level
}else if(d.type == 2){/*股东*/
d.level = "#4cd1e0";return d.level
}else if(d.type == 3){/*对外投资*/
d.level = "#92db8c";return d.level
}});
var labelText = level_groups.append("text").attr('dx', diameter/2 - 80).attr("dy","18").attr("text-anchor", "end").text(function(d){ return d.type; }).style('stroke',"#000");/*文字末尾对齐，颜色#000*/
});

``````  d3.select(self.frameElement).style("height", diameter - 150 + "px");

</script>

以下为json数据：
{
"id": "736c799c-7765-4e02-ab83-b57d7716d7bb",
"name": "品尚电子商务有限公司",
"type": 1,
"level": "#09f",
"children": [{
"id": "bfed1dd8-3228-4e36-9577-3d94ac16f8ab",
"name": "民生电商控股（深圳）有限公司",
"type": 2,
"level": "#09f",
}]
``````

}

``````
``````

1个回答

dabocaiqq   2017.02.15 23:53