Published
Edited
Dec 13, 2021
4 stars
Insert cell
Insert cell
{
// USER DEFINED VARS
// set outer width and height for svg
const width = window.innerWidth * .9
const height = width * 2/3
// user defined: size of grid and # cells
const nrows = 10;
const ncols = 29;
// CHART STUFF
// chart constants
const margin = {
top: 60,
bottom: 30,
left: 60,
right: 50
}
// params for chart itself.
const gridWidth = width - margin.left - margin.right;
const gridHeight = height - margin.bottom - margin.top;
// make svg (use margin convention for spacing)
const svg = DOM.svg(
gridWidth + margin.left + margin.right,
gridHeight + margin.bottom + margin.top
)
const svgSel = d3.select(svg)
const sel = svgSel.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`)
svgSel.style('border', '1px solid black')
// calculate cell size dynamically based on user input
const cellWidth = gridWidth / ncols;
const cellHeight = gridHeight / nrows;
// define scales to be dynamic based on grid size
const gridXScale = d3.scaleLinear().domain([0, ncols]).range([0, gridWidth]);
const gridYScale = d3.scaleLinear().domain([0, nrows]).range([0, gridHeight]);
// init grid data
let data = []
// loop thru and generate desired grid data
// let cell = 0;
for (let rowNumber = 0; rowNumber < nrows; rowNumber++) {
for (let colNumber = 0; colNumber < ncols; colNumber++) {
let obs = {
x: colNumber,
y: rowNumber,
height: cellHeight,
width: cellWidth
};
// add data to data
data.push(obs)
// increment cell count
// cell++
}
}

// create g tags to append to (in grid shape)
const join = sel.selectAll('g.grid')
.data(data)
.enter().append('g')
.attr('class', 'grid')
.attr('transform', (d, i) => {
return `translate(${gridXScale(d.x)}, ${gridYScale(d.y)})`
})

const circlePadding = 2
// append whatever in grid; circles here
sel.selectAll('g.grid').each(function(d,i) {
const cell = d3.select(this).append('g')
// append circles
cell.append('circle')
.attr('r', cellWidth / 2 - circlePadding)
.attr('fill', 'red')
});
return svg
}
Insert cell
d3 = require("d3@6")
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