Public
Edited
Sep 30, 2023
Importers
1 star
Insert cell
Insert cell
gridModulo(data, {
columnLength: numOfColumns,
squareSize: squareSize
})
Insert cell
Insert cell
Insert cell
data = d3.range(numberOfSquares)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function gridModulo (data, {
dataLength = data.length,
columnLength = 0,
squareSize = 50,
squareCol = "#66ab56",
strokeCol = "#fff",
strokeWidth = 2,
textFill = "#fff",
showValues = true
} = {}) {

const size = (squareSize + (strokeWidth * 2));
const columns = (columnLength !== null && columnLength > 1 ) ? columnLength : Math.round(width / size) ;
const height = (dataLength / columns) * size;

console.log('columns', columns)
const svg = DOM.svg(width, height + size);
const sel = d3.select(svg);

const scaleCol = d3.scaleLinear()
.domain([0, columns])
.range([0, columns * size]);

const scaleRow = d3.scaleLinear()
.domain([0, dataLength / columns])
.range([0, height]);

const join = sel.selectAll('g')
.data(data)
.join('g').append('g')
.attr('transform', (d, i) => {
const x = i % columns
const y = Math.floor(i / columns)
return `translate(${scaleCol(x)}, ${scaleRow(y)})`
});

join.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', squareSize)
.attr('height', squareSize)
.attr('stroke-width', strokeWidth)
.attr('stroke', strokeCol)
.attr('fill', squareCol);

// show some values so we can confirm the ordering
if (showValues) {
join.append('text')
.attr('x', squareSize / 2 )
.attr('y', squareSize / 2)
.attr('dy', 5)
.attr('text-anchor', 'middle')
.style('font-size', '13px')
.style('font-family', 'monospace')
.style('fill', textFill)
.text(d => d);
}
return svg;
}
Insert cell
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