home/ atoms/ treemap-data-driven-styling

Treemap boxes can be styled with callback functions that receive value and index, enabling data-driven colour

The styles API in treemap-squared accepts either static CSS properties or a function(coordinates, index){} for box, label, and background slots. The index parameter is a nested array path matching the data nesting depth, so index [1,1] refers to the second item in the second group. This lets you encode value in saturation or brightness: compute colour from the data point found by walking the index into the data array, then return a style object. The pattern — callback receives coordinates plus identity, returns style — recurs across many p5.js and D3 APIs and is worth recognising as a generic data-driven-styling idiom.

Examples

var boxFormatter = function(coordinates, index) { var datapoint = data; for(var i=0;i<index.length;i++){datapoint=datapoint[index[i]];} var sat = (datapoint/60000)*0.6+0.4; return {fill:‘hsb(0.2,‘+sat+‘,0.5)’}; }; Treemap.draw(‘el’, 600, 200, data, labels, {box: boxFormatter});

Assessment

Write a boxFormatter function that colours boxes red for values above 50000 and blue otherwise. Pass it as styles[‘box’] to Treemap.draw() and verify.

“Styling can also be done using functions as demonstrated in this chart in which the shade of the box depends on the value of the data point it represents.”
corpus · generative-design-bohnacker-gross-laub-lazzeroni-official-p5 · chunk 54