Published
Edited
Jun 24, 2020
Insert cell
Insert cell
chart = {
const treemap = d3.treemap()
.size([width, height])
.padding(1)
const hierarchy_data = d3.hierarchy(data)
.sum(d => d.value)//遍历子节点的value值并累加作为当前节点的value 这个是构造treemap必须的
.sort((a, b) => a.value - b.value)
const root = treemap(hierarchy_data);//构造使用层次数据构造treemap数据结构,返回根节点

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("font", "10px sans-serif");

const leaf = svg.selectAll("g")
.data(root.leaves())//返回全部叶子节点 以上这些节点如果不理解的话可以输出来看看
.join("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`);

leaf.append("title")
.text(d => `${d.ancestors().reverse().map(d => d.data.name).join("/")}\n${format(d.value)}`);

leaf.append("rect")
.attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); })
.attr("fill-opacity", 0.6)
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0);

leaf.append("clipPath") //限定绘制范围为数据对应的矩形大小,超出矩形的的文字不绘制
.attr("id",d=>(d.clipUid = d.data.name+"_clip"))//设置id并在数据结构中新建clipUid属性方便下面引用
.append("rect")//矩形大小同上
.attr("width",d=>d.x1-d.x0)
.attr("height",d=>d.y1-d.y0)
leaf.append("g")
.attr("clip-path",d=>`url(#${d.clipUid})`)//引用clipPath来限制绘制范围
.selectAll("text")
.data(d => d.data.name.split(/(?=[A-Z][a-z])|\s+/g).concat(format(d.value)))
.join("text")
.attr("x",3)
.attr("y",(d,i)=>(i+1)*10)
.text(d=>d)

return svg.node();
}
Insert cell
data = FileAttachment("flare-2.json").json()
Insert cell
width = 954
Insert cell
height = 954
Insert cell
format = d3.format(",d")
Insert cell
color = d3.scaleOrdinal(d3.schemeCategory10)
Insert cell
d3 = require("d3@5")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more