D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jwilber
Full window
Github gist
simple treemap flat data
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> const margin = {top: 50, right: 25, bottom: 25, left: 50}; const height = 600 - margin.top - margin.bottom; const width = 600 - margin.right - margin.left; const svg = d3.select('body') .append('svg') .attr('width', width + margin.right + margin.left) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('class', 'palette') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); const data = [ {color:"d3.rgb(12, 27, 199)", percentage: .100, img_url: ''}, {color:"d3.rgb(180, 5, 65)", percentage: .20, img_url: ''}, {color:"d3.rgb(120, 67, 199)", percentage: .24, img_url: ''}, {color:"d3.rgb(120, 167, 199)", percentage: .30, img_url: ''}, {color:"d3.rgb(11.5, 102.5, 3.5)", percentage: .09, img_url: ''} ]; data.forEach(function(d) { d.color = d.color; d.percentage = +d.percentage; }); const nest = d3.nest() .key(d => d.color) .rollup(v => d3.sum(v, vals => vals.percentage)) .entries(data); const treemapLayout = d3.treemap() .size([50, 70]) .paddingOuter(1); const root = d3.hierarchy({values: nest}, d => d.values) .sum(d => d.value) // .sort( (a, b) => b.value - a.value); treemapLayout(root); d3.select('.palette') .selectAll('rect') .data(root.descendants()) .enter() .append('rect') .attr("class", "rect") .attr('x', d => d.x0) .attr('y', d => d.y0) .attr('width', d => d.x1 - d.x0) .attr('height', d => d.y1 - d.y0) .attr('fill', d => eval(d.data.key) || 'white') .attr('stroke', 'black') .attr('stroke-width', 1) .style('opacity', 1); const HOVER_SCALE = 5; const HOVER_POS = 2; d3.select('.palette') .on("mouseover", highlight) .on("mouseout", deHightlight); function highlight(d) { d3.selectAll('rect.rect') .transition() .attr('x', d => d.x0 + HOVER_POS) .attr('y', d => d.y0 - HOVER_POS) .attr('width', d => d.x1 + HOVER_SCALE - d.x0 ) .attr('height', d => d.y1 + HOVER_SCALE - d.y0) .attr('stroke-width', 3.5) }; function deHightlight(d) { d3.selectAll('rect.rect') .transition() .attr('x', d => d.x0) .attr('y', d => d.y0) .attr('width', d => d.x1 - d.x0) .attr('height', d => d.y1 - d.y0) .attr('stroke-width', 1) }; </script> </body>
https://d3js.org/d3.v4.min.js