D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
tomshanley
Full window
Github gist
Unit chart
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;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> let chartWidth = 500 let unitWidth = 10 let unitShape = "circle" let cats = 54 // % //let dogs = 29 // % //let mice = 12 // % generateUnitChart(cats, unitWidth, chartWidth, unitShape) //generateUnitChart(dogs, unitWidth, chartWidth)) //generateUnitChart(mice, unitWidth, chartWidth)) function generateUnitChart(pct, _unitWidth, _chartWidth, _unitShape) { let totalUnits = _unitWidth * _unitWidth let unitArray = createUnitArray(pct, totalUnits) drawUnitChart(unitArray, _unitWidth, _chartWidth, _unitShape) } function createUnitArray(n,t) { let cutoff = Math.round((t/100) * n) return d3.range(t).map(function(d, i) { return i < cutoff ? "y" : "n" }) } function drawUnitChart(data, uw, cw, s) { let chartWH = cw let margin = 10 let scaleDomain = d3.range(uw) let scalePadding = 0.2 let xScale = d3.scaleBand() .domain(scaleDomain) .range([0, chartWH]) .padding(scalePadding) let yScale = d3.scaleBand() .domain(scaleDomain) .range([chartWH, 0]) .padding(scalePadding) let svg = d3.select("body").append("svg") .attr("width", chartWH + margin + margin) .attr("height", chartWH + margin + margin) let g = svg.append("g") .attr("transform", "translate(" + margin + "," + margin + ")") let units = g.selectAll(".unit") .data(data) .enter() .append("g") .attr("class", "unit") .attr("transform", function(d, i){ return "translate(" + xScale(xCoord(i, uw)) + "," + yScale(yCoord(i, uw)) + ")" }) if (s == "circle") { let circleR = xScale.bandwidth() / 2 units.append("circle") .attr("cx", circleR) .attr("cy", circleR) .attr("r", circleR) } else { let squareWidth = xScale.bandwidth() units.append("rect") .attr("rx", 5) .attr("width", squareWidth) .attr("height", squareWidth) } units.style("fill", function(d){ return d == "y" ? "FireBrick" : "LightSteelBlue" }) } function yCoord(n, s) { return (Math.floor(n/s)) } function xCoord(n, s) { return n - ((Math.floor(n/s)) * s); } </script> </body>
https://d3js.org/d3.v4.min.js