Published
Edited
Dec 18, 2019
Insert cell
md`# Treemap Cash Flows`
Insert cell
Insert cell
chart = {
const root = treemap(data);
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width + margin.left + margin.right, height + margin.top + margin.bottom])
.style("font", "10px sans-serif")

const leaf = svg.selectAll("g")
.data(root.leaves())
.join("g")
.attr("transform", d => `translate(${d.x0 + margin.left}, ${d.y0 + margin.top})`)

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

leaf.append("rect")
.attr("id", d => (d.leafUid = DOM.uid("leaf")).id)
.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 = DOM.uid("clip")).id)
.append("use")
.attr("xlink:href", d => d.leafUid.href)

leaf.append("text")
.attr("clip-path", d => d.clipUid)
.selectAll("tspan")
.data(d => d.data.name.split(/(?=[A-Z][^A-Z])/g).concat(format(d.value)))
.join("tspan")
.attr("x", 3)
.attr("y", (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`)
.attr("fill-opacity", (d, i, nodes) => i === nodes.length - 1 ? 0.7 : null)
.text(d => d)
svg.append('g')
.selectAll('.legend-group')
.data(data.children)
.join('g')
.attr('class', 'legend')
.attr('transform', (d, i) => `translate(${15 + i * 70}, 15)`)
.append('rect')
.attr('fill', (d) => color(d.name))
.attr('opacity', 0.7)
.attr('width', 15)
.attr('height', 15)
.attr('rx', 3)
svg.selectAll('.legend')
.append('text')
.attr('font-size', 12)
.attr('transform', (d, i) => `translate(19, 12)`)
.text((d) => d.name)
return svg.node()
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
width = 800
Insert cell
height = 900
Insert cell
margin = ({ top: 50, right: 5, bottom: 5, left: 5 });
Insert cell
Insert cell
color = d3.scaleOrdinal(d3.schemeCategory10)
Insert cell
d3 = require("d3@5")
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