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

相关推荐
188号安全攻城狮1 分钟前
【前端基础知识】JavaScript 数组方法总结:从表格速查到分类详解
开发语言·前端·javascript·网络安全
qq_381338501 分钟前
微前端架构深度实践:从 qiankun 到 Module Federation 的企业级方案
前端·架构
鱼干~5 分钟前
【全栈知识点】全栈开发知识点
前端·人工智能·c#
英俊潇洒美少年6 分钟前
迷你 React 调度器(带优先级+时间切片)手写实现
前端·javascript·react.js
chQHk57BN9 分钟前
PWA开发指南:构建可离线使用的渐进式Web应用
前端
小白学大数据13 分钟前
告别复杂 XPath:DeepSeek+Python 爬虫快速实践
开发语言·爬虫·python·selenium
weixin_4080996716 分钟前
【保姆级教程】按键精灵调用 OCR 文字识别 API(从0到1完整实战 + 可运行脚本)
java·前端·人工智能·后端·ocr·api·按键精灵
AI_Claude_code20 分钟前
ZLibrary访问困境方案六:自建RSS/Calibre内容同步服务器的完整指南
运维·服务器·网络·爬虫·python·tcp/ip·http
xdl259922 分钟前
CSS flex 布局中没有 justify-items
前端·css
百撕可乐22 分钟前
WenDoraAi官网NextJS实战04:HTTP 请求封装与SSR
前端·网络·网络协议·react.js·http