[技术小技巧] 可视化分析:在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还没有下载好,因此找不到,可以等一会儿再运行。

相关推荐
张拭心4 小时前
Cursor 又偷偷更新,这个功能太实用:Visual Editor for Cursor Browser
前端·人工智能
I'm Jie4 小时前
深入了解 Vue 3 组件间通信机制
前端·javascript·vue.js
用户90443816324605 小时前
90%前端都踩过的JS内存黑洞:从《你不知道的JavaScript》解锁底层逻辑与避坑指南
前端·javascript·面试
CodeCraft Studio6 小时前
文档开发组件Aspose 25.12全新发布:多模块更新,继续强化文档、图像与演示处理能力
前端·.net·ppt·aspose·文档转换·word文档开发·文档开发api
这个人懒得名字都没写6 小时前
Python包管理新纪元:uv
python·conda·pip·uv
有泽改之_6 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
是毛毛吧6 小时前
边打游戏边学Python的5个开源项目
python·开源·github·开源软件·pygame
PPPPickup6 小时前
easychat项目复盘---获取联系人列表,联系人详细,删除拉黑联系人
java·前端·javascript
老前端的功夫6 小时前
前端高可靠架构:医疗级Web应用的实时通信设计与实践
前端·javascript·vue.js·ubuntu·架构·前端框架