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

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

js 复制代码
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 复制代码
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代码。

py 复制代码
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还没有下载好,因此找不到,可以等一会儿再运行。

相关推荐
孤狼warrior14 分钟前
灰色预测模型
人工智能·python·算法·数学建模
Rrvive14 分钟前
localhost 和 127.0.0.1 的核心区别
前端
蓝倾15 分钟前
如何使用Python通过API接口批量抓取小红书笔记评论?
前端·后端·api
極光未晚17 分钟前
JavaScript BOM 对象:浏览器的隐形控制塔
前端·javascript·源码
天涯学馆18 分钟前
网站秒变 App!手把手教你搞定 PWA
前端·javascript·面试
神仙别闹19 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
uu_code00722 分钟前
Android接入Pixelfree美颜SDK技术指南
前端
小鱼小鱼干23 分钟前
使用 ESLint 实现 Git Commit 前的语法检查
前端
码哥DFS39 分钟前
Flex布局原理
前端·css·css3
机器学习之心1 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络