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

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more