使用d3.js可视化解析树

时间:2016-07-06 11:15:00

标签: javascript html d3.js parse-tree

我一直在尝试通过生成使用d3.js绘制树的HTML文件来获取解析树的直观表示。该文件如下所示:

<!DOCTYPE html>
<meta charset="utf-8">
<head><title> Tree Visualization </title></head>
<script src="https://d3js.org/d3.v3.min.js"></script>

<script type="text/javascript">
    function drawTree(o) {
        d3.select("#"+o.divID).select("svg").remove() 

        var viz = d3.select("#"+o.divID)
            .append("svg")
            .attr("width", o.width)
            .attr("height", o.height)  

        var vis = viz.append("g")
            .attr("id","treeg")
            .attr("transform", "translate("+ o.padding +","+ o.padding +")") 

        var tree = d3.layout.tree()
            .size([o.width - (2 * o.padding), o.height - (2 * o.padding)]);

        var diagonal = d3.svg.diagonal()
            .projection(function(d) { return [d.x, d.y]; });

        var nodes = tree.nodes(o.treeData);

        var link = vis.selectAll("pathlink")
            .data(tree.links(nodes)).enter()
            .append("path")
            .attr("class", "link")
            .attr("d", diagonal)

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

        node.append("circle")
            .attr("r", 10)
            .style("fill", function(d) { return (d.children) ? "#E14B3B" : "#1C8B98" });

        node.append("svg:text")
            .attr("dx", function(d) { return d.children ? 0 : 0; })
            .attr("dy", function(d) { return d.children ? 5 : 5; })
            .attr("text-anchor", function(d) { return d.children ? "middle" : "middle"; })
            .style("fill", "white").text(function(d) { return d.name; })
    }
 </script>

<body onLoad="drawTree({divID: 'viz', width: 600, height: 400, padding: 50, treeData: {name: 'S', children: [{name: 'S', children: [{name: 'S', children: [{name: 'S', children: [{name: 'x'}]}, {name: 'S', children: [{name: 'y'}]}, {name: '*'}]}, {name: 'S', children: [{name: '1'}]}, {name: '+'}]}, {name: 'S', children: [{name: 'S', children: [{name: '1'}]}, {name: '-'}]}, {name: '+'}]}})">
<div id="viz"></div>
</body>
</html>

我希望它看起来像: this

目前的情况如下: this

我对d3.js完全陌生,而且说实话,代码来自一个示例,只有我修改过。我设法以这种方式达到了这一点,但我无法弄清楚它出错的地方。

我很感激每一点帮助。提前谢谢!

1 个答案:

答案 0 :(得分:2)

需要更新样式。添加以下行

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 2px;
}

对于节点圆边框

circle {
  stroke: #000;
  stroke-width: 1px;
}  

工作fiddle