Published
Edited
Mar 10, 2018
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
/**
* Draw a cartesian coordinate grid
*
* @param {Object} canvas - Required. The SVG d3.selection ex) `d3.select(DOM.svg(WIDTH, HEIGHT));`
* @param {array} [size=[500, 500]] - The canvas dimensions
* @param {array} [xDomain=[-1, 1]] - The x domain. Defaults to "unit" grid.
* @param {array} [yDomain=[-1, 1]] - The y domain. Defaults to "unit" grid.
* @param {number} [padding=10] - Padding
*/
CartesianGrid = (canvas, height = 400, xDomain=[1, -1], yDomain=[-1, 1], padding=10 ) => {
/* "Canvas" setup */
let ownCanvas = false;
if (!canvas) {
ownCanvas = true;
canvas = d3.select(DOM.svg(width, height));
}

// Create a grid SVG element
const grid = canvas.append('g').attr("class", "grid grid--cartesian");
// Define the axes scales
const xScale = d3.scaleLinear().domain(xDomain).range([width - padding, padding]);
const yScale = d3.scaleLinear().domain(yDomain).range([height - padding, padding]);
// Define the axes
const yAxis = d3.axisLeft(yScale);
const xAxis = d3.axisBottom(xScale)
// Plot the x-axis
const xAxisPlot = grid.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + (height / 2) +")")
.call(xAxis.tickSize(-height, 0, 0));

// Plot the y-axis
const yAxisPlot = grid.append("g")
.attr("class", "axis axis--y")
.attr("transform", "translate("+ (width/2) +",0)")
.call(yAxis.tickSize(-width, 0, 0));

// Add the x-axis lines/ticks
xAxisPlot.selectAll(".tick line")
.attr("stroke", "silver")
.attr("y1", (width - (2*padding))/2 * -1)
.attr("y2", (width - (2*padding))/2 * 1);

// Add the y-axis lines/ticks
yAxisPlot.selectAll(".tick line")
.attr("stroke", "silver")
.attr("x1", (width - (2*padding))/2 * -1)
.attr("x2", (width - (2*padding))/2 * 1);
if (ownCanvas) {
return canvas.node();
}
}
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