2014-03-29 421 views
5

下图是使用D3.js生成的。如何从Python生成D3.js圆形树状图代码

enter image description here

基于代码here

<!DOCTYPE html> 
<meta charset="utf-8"> 
<title>Flare Dendrogram</title> 
<style> 

.node circle { 
    fill: #fff; 
    stroke: steelblue; 
    stroke-width: 1.5px; 
} 

.node { 
    font: 10px sans-serif; 
} 

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

</style> 
<body> 
<script src="http://d3js.org/d3.v3.min.js"></script> 
<script> 

var radius = 960/2; 

var cluster = d3.layout.cluster() 
    .size([360, radius - 120]); 

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", radius * 2) 
    .attr("height", radius * 2) 
    .append("g") 
    .attr("transform", "translate(" + radius + "," + radius + ")"); 

d3.json("/d/4063550/flare.json", function(error, root) { 
    var nodes = cluster.nodes(root); 

    var link = svg.selectAll("path.link") 
     .data(cluster.links(nodes)) 
    .enter().append("path") 
     .attr("class", "link") 
     .attr("d", diagonal); 

    var node = svg.selectAll("g.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", 4.5); 

    node.append("text") 
     .attr("dy", ".31em") 
     .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) 
     .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) 
     .text(function(d) { return d.name; }); 
}); 

d3.select(self.frameElement).style("height", radius * 2 + "px"); 

</script> 

有没有一种方法,我可以使用Python产生上述确切的数字(HTML)?

+2

当然还有一个办法 - 你只需要重新编写d3.js图书馆和蟒蛇DOM的所有相关部分 - 但是这可能不是你想听到的。你能更清楚地解释*为什么*你想使用python而不是Javascript?也许有另一种方法可以在不重新发明轮子的情况下满足你的目标。 – AmeliaBR

回答

4

假设您想要避免必须编写JavaScript并使用python代替,您可以查看一下pyjs。从他们website

pyjs contains a Python-to-JavaScript compiler, an AJAX framework and a 
Widget Set API. pyjs started life as a Python port of Google Web Toolkit, 
the Java-to-JavaScript compiler. 

我还没有使用它,我不能确定你将如何去包括D3库。但他们的wiki有以下页面:

https://github.com/pyjs/pyjs/wiki/Calling-a-jQuery-component-from-Pyjs

这篇文章可能会给你是否pyjs是对你有用的想法。

2

有没有一种方法可以使用Python来生成上面的确切数字(HTML)?

pandita's suggestion不太相似,您可以使用Brython,它允许您在Web浏览器中运行Python。一些示例框架代码(使用D3.js;我不知道给你D3.js.好一个树状图产生的任何Python库):

<!DOCTYPE html> 
<meta charset="utf-8"> 
<title>Flare Dendrogram</title> 
<style> 
/* CSS goes here */ 
</style> 

<script src="http://d3js.org/d3.v3.min.js"></script> 
<script src="brython.js"></script> 
<script type="text/python"> 
# 
# Python code to generate dendogram here 
# (equivalent to the sample JavaScript code provided) 
# 
</script> 


<body onload="brython()"> 
</body> 
</html> 

但是这似乎并不像一个伟大的解。

您也可能会发现这个StackOverflow的页面有所帮助:How do I create a radial cluster like the following code-example in Python?