Published
Edited
May 23, 2021
Insert cell
Insert cell
Insert cell
Insert cell
d3.range(3)
Insert cell
Insert cell
d3.cross([0, 1, 2], [3, 4, 5])
Insert cell
d3.cross(d3.range(3), d3.range(3))
Insert cell
Insert cell
d3.zip([0, 1, 2], ['cat', 'dog', 'mouse'])
Insert cell
Insert cell
numRows = 5
Insert cell
numCols = 6
Insert cell
Insert cell
coordinates = d3.cross(d3.range(numRows), d3.range(numCols))
Insert cell
Insert cell
gridPositions = coordinates.map(([row, col]) => ({row, col}))
Insert cell
Insert cell
pairings = d3.zip(lettersAndWords, gridPositions)
Insert cell
Insert cell
data = pairings.map(([data, pos]) => ({...data, ...pos}))
Insert cell
Insert cell
{
// the usual set up

const margin = { top: 10, bottom: 10, right: 10, left: 10 };
const visHeight = 500 - margin.top - margin.bottom;
const visWidth = width - margin.left - margin.right;
const svg = d3.create('svg')
.attr('width', visWidth + margin.left + margin.right)
.attr('height', visHeight + margin.top + margin.bottom);
const g = svg.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
// create scales to place the grid cells
const row = d3.scaleBand()
.domain(d3.range(numRows))
.range([0, visHeight])
.padding(0.05);
const col = d3.scaleBand()
.domain(d3.range(numCols))
.range([0, visWidth])
.padding(0.05);
// add a group for each cell and position it according to its row and column
const cells = g.append('g')
.selectAll('g')
.data(data)
.join('g')
.attr('transform', d => `translate(${col(d.col)}, ${row(d.row)})`);
// add a rectangle to each group and make it take up the entire cell
cells.append('rect')
.attr('width', col.bandwidth())
.attr('height', row.bandwidth())
.attr('fill', 'white')
.attr('stroke', 'red');
// add the list of words to each group
cells.selectAll('text')
.data(d => d.words)
.join('text')
.attr('font-size', 15)
.attr('font-family', 'sans-serif')
.attr('dominant-baseline', 'hanging')
.attr('x', 5)
.attr('y', (d, i) => i * 15 + 2)
.text(d => d);
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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