Published
Edited
Feb 24, 2021
1 fork
Importers
3 stars
Insert cell
Insert cell
Insert cell
data = generateRandomData(100)
Insert cell
margin = ({ left: 25, right: 25, top: 25, bottom: 25 })
Insert cell
xRange = [margin.left, width - margin.right]
Insert cell
Insert cell
xScale.ticks()
Insert cell
xScale.ticks(20) // The count parameter is only a hint
Insert cell
xScale.tickFormat()
Insert cell
md`### Draw Axis Bottom`
Insert cell
Insert cell
drawXaxis = (context, xScale, Y, xExtent) => {
const [startX, endX] = xExtent;
let tickSize = 6,
xTicks = xScale.ticks(), // You may choose tick counts. ex: xScale.ticks(20)
xTickFormat = xScale.tickFormat(); // you may choose the format. ex: xScale.tickFormat(tickCount, ".0s")

context.strokeStyle = "black";

context.beginPath();
xTicks.forEach(d => {
context.moveTo(xScale(d), Y);
context.lineTo(xScale(d), Y + tickSize);
});
context.stroke();

context.beginPath();
context.moveTo(startX, Y + tickSize);
context.lineTo(startX, Y);
context.lineTo(endX, Y);
context.lineTo(endX, Y + tickSize);
context.stroke();

context.textAlign = "center";
context.textBaseline = "top";
context.fillStyle = "black";
xTicks.forEach(d => {
context.beginPath();
context.fillText(xTickFormat(d), xScale(d), Y + tickSize);
});
}
Insert cell
md`### Draw Axis Left`
Insert cell
Insert cell
drawYaxis = (context, yScale, X, yExtent) => {
const [startY, endY] = yExtent;

const tickPadding = 3,
tickSize = 6,
yTicks = yScale.ticks(),
yTickFormat = yScale.tickFormat();

context.strokeStyle = "black";
context.beginPath();
yTicks.forEach(d => {
context.moveTo(X, yScale(d));
context.lineTo(X - tickSize, yScale(d));
});
context.stroke();

context.beginPath();
context.moveTo(X - tickSize, startY);
context.lineTo(X, startY);
context.lineTo(X, endY);
context.lineTo(X - tickSize, endY);
context.stroke();

context.textAlign = "right";
context.textBaseline = "middle";
context.fillStyle = "black";
yTicks.forEach(d => {
context.beginPath();
context.fillText(yTickFormat(d), X - tickSize - tickPadding, yScale(d));
});
}
Insert cell
generateRandomData()
Insert cell
Insert cell
md`## External Libraries and Imports`
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