Published
Edited
Mar 4, 2018
1 fork
Importers
1 star
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, size=[500, 500], xDomain=[1, -1], yDomain=[-1, 1], padding=10 ) => {

// Create a grid SVG element
const grid = canvas.append('g').attr("class", "grid grid--cartesian");
// Setup the dimensions
const height = size[1]; //canvas.node().clientHeight;
const width = size[0]; //canvas.node().clientWidth;

// 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);
}
Insert cell
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