Skip to content

Instantly share code, notes, and snippets.

@afcondon
Created April 23, 2020 15:32
Show Gist options
  • Save afcondon/3eb12ff2bd551385de2276ae394c4b79 to your computer and use it in GitHub Desktop.
Save afcondon/3eb12ff2bd551385de2276ae394c4b79 to your computer and use it in GitHub Desktop.
d3.join(enter, update, exit) with multiple elements
var chart = function (data) {
var root = treemap(data)
svg
.selectAll('g')
.data(root.leaves(), d => d.data.id)
.join(
enter => enterBoxAndName(enter),
update => updateBoxAndName(update)
)
.attr('transform', d => `translate(${d.x0},${d.y0})`)
return svg.node()
}
var treemap = function (data) {
var result = d3
.treemap()
.tile(d3.treemapSquarify)
.size([width, height])
.padding(1)
.round(true)(
d3
.hierarchy(data)
.sum(d => d.value)
.sort((a, b) => b.value - a.value)
)
return result
}
function calcWidth (d) {
return d.x1 - d.x0
}
function calcHeight (d) {
return d.y1 - d.y0
}
function updateBoxAndName (update) {
update.select('rect')
.attr('width', calcWidth)
.attr('height', calcHeight)
// ***** This just here so you can test which nodes got updated, at present no need to change text
// update.select('text')
// .attr('fill', 'red')
return update
}
function enterBoxAndName (enter) {
var leaf = enter.append('g')
leaf
.append('rect')
.attr('id', d => (d.leafUid = DOM.uid('leaf')).id)
.attr('fill', d => {
return color(d.data.color)
})
.attr('fill-opacity', 0.6)
.attr('width', calcWidth)
.attr('height', calcHeight)
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)
.text(d => d.data.name)
.attr('x', 3)
.attr('y', 15)
return leaf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment