Published
Edited
Sep 14, 2020
1 fork
11 stars
Insert cell
Insert cell
categorized = [
{ emoji: "🍏", type: "fruit", value: 45 },
{ emoji: "🍎", type: "fruit", value: 25 },
{ emoji: "🍐", type: "fruit", value: 15 },
{ emoji: "🍊", type: "fruit", value: 35 },
{ emoji: "🍋", type: "fruit", value: 5 },
{ emoji: "🍌", type: "fruit", value: 25 },
{ emoji: "🍉", type: "fruit", value: 15 },
{ emoji: "🥕", type: "vegetable", value: 45 },
{ emoji: "🥦", type: "vegetable", value: 35 },
{ emoji: "🥬", type: "vegetable", value: 25 },
{ emoji: "🥒", type: "vegetable", value: 15 },
{ emoji: "🍆", type: "vegetable", value: 15 },
{ emoji: "🧅", type: "vegetable", value: 35 },
]
Insert cell
chart = {
let tree = treemap(root)
let svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
let leaf = svg.selectAll("g")
.data(tree.leaves())
.join("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`)

leaf.append("rect")
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0)
// .attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name) })
.attr("fill", d => { return color(d.data.name) })
.attr("fill-opacity", 0.2)
leaf.append("text")
.selectAll("tspan")
.data(d => d3.range(d.value).map(i => ({ name: d.data.name, parent: d}) ))
.join("tspan")
.attr("x", (d,i,nodes) => {
let w = d.parent.x1 - d.parent.x0 - 5
let n = Math.floor(w / emojiSize)
return 3 + (i % n) * emojiSize
})
.attr("y", (d,i,nodes) => {
let w = d.parent.x1 - d.parent.x0 - 5
let n = Math.floor(w / emojiSize)
return 25 + Math.floor(i/n) * emojiSize
})
.style("font-size", `${emojiSize}px`)
.text(d => d.name)
return svg.node()
}
Insert cell
grouped = d3.group(categorized, d => d.type)
Insert cell
data = ({
name: "foods",
children: Array.from(grouped, ([d, children]) => {
return {
name: d,
children: children.map(c => {
return { ...c, name: c.emoji }
})
}
})
})
Insert cell
root = d3.hierarchy(data)
.sum(d => d.value)
.sort((a,b) => b.value - a.value)
Insert cell
treemap = d3.treemap()
.tile(d3.treemapSquarify)
.size([width, height])
.padding(1)
// .round(true)
Insert cell
height = 420
Insert cell
emojiSize = 25
Insert cell
color = d3.scaleOrdinal(d3.schemeCategory10)
Insert cell
d3 = require("d3@6")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more