[技术小技巧] 可视化分析:在jupyter中使用d3可视化树形结构

发布于:2024-04-30 ⋅ 阅读:(27) ⋅ 点赞:(0)

首先在python中定义一个字符串,记录d3.js绘制属性图的js脚本代码模版。其中{{data}}就是将来要被替换的内容。

d3_code_template = """
// 创建树状结构数据
var treeData = {{data}};

// 创建d3树布局
var margin = { top: 20, right: 90, bottom: 30, left: 90 },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var svg = d3
  .select("#tree")
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var treemap = d3.tree().size([height, width]);

var nodes = d3.hierarchy(treeData);
nodes = treemap(nodes);

var link = svg
  .selectAll(".link")
  .data(nodes.descendants().slice(1))
  .enter()
  .append("path")
  .attr("class", "link")
  .attr("d", function (d) {
    return (
      "M" + d.y + "," + d.x +
      "C" + (d.y + d.parent.y) / 2 + "," + d.x +
      " " + (d.y + d.parent.y) / 2 + "," + d.parent.x +
      " " + d.parent.y + "," + d.parent.x
    );
  });

var node = svg
  .selectAll(".node")
  .data(nodes.descendants())
  .enter()
  .append("g")
  .attr("class", function (d) {
    return "node" + (d.children ? " node--internal" : " node--leaf");
  })
  .attr("transform", function (d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

node.append("circle").attr("r", 10);

node
  .append("text")
  .attr("dy", ".35em")
  .attr("x", function (d) {
    return d.children ? -13 : 13;
  })
  .style("text-anchor", function (d) {
    return d.children ? "end" : "start";
  })
  .text(function (d) {
    return d.data.name;
  });
"""

定义一个字符串,记录html的模版。其中“// 在这里插入d3.js代码”就是将来要被替换的部分。

html_template = """
<style>
.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}
</style>

<svg id="tree" width="960" height="500"></svg>

<script src="https://d3js.org/d3.v5.min.js"></script>

<script>
// 在这里插入d3.js代码
</script>
"""

在jupyter中import入这两个变量,编写可视化的Demo代码。

from IPython.display import display, HTML

tree_data = {
  "name": "Root",
  "children": [
    {
      "name": "Node 1",
      "children": [
        { "name": "Node 1.1" },
        { "name": "Node 1.2" },
        { "name": "Node 1.3" },
      ]
    },
    {
      "name": "Node 2",
      "children": [
        { "name": "Node 2.1" },
        { "name": "Node 2.2" },
        { "name": "Node 2.3" }
      ]
    }
  ]
}

d3_code = d3_code_template.replace(r'{{data}}', str(tree_data)) 
print(d3_code)

html_content = html_template.replace("// 在这里插入d3.js代码", d3_code)
display(HTML(html_content))

呈现结果如下:

在这里插入图片描述
可以是用F12 debug和前端开发类似,比如下面这个报错,是因为d3还没有下载好,因此找不到,可以等一会儿再运行。
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到