Published
Edited
May 12, 2020
Fork of D3 Template
Insert cell
Insert cell
Insert cell
{
const values = [{ x:1,y: 10 }, { x: 2, y: 5 }, { x: 3, y: 40 }];
const width = 700;
const height = width * 0.75;
const margin = {
left: 40,
top: 20,
right: 10,
bottom: 40
};

// Create SVG Element
const node = DOM.svg(
width + margin.left + margin.right,
height + margin.top + margin.bottom
);

// x-scale
const x = d3
.scaleLinear()
.domain([0, d3.max(values, d => d.x)])
.range([0, width])
.interpolate(d3.interpolateRound);

// y-scale
const y = d3
.scaleLinear()
.domain([0,d3.max(values, d => d.y)])
.range([height, margin.top])
.interpolate(d3.interpolateRound);

const svg = d3.select(node);

// Axis - transform (0, 0) -> (margin.left, margin.top)
const axis = svg
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);

axis
.append('g')
.attr('transform', `translate(0, ${height})`) // Put x-axis at bottom
.call(d3.axisBottom(x));
axis.append('g').call(d3.axisLeft(y));

const line = d3
.line()
.x(d => x(d.x)) // scale x
.y(d => y(d.y)); // scale y

axis
.append('path')
.attr('d', line(values))
.attr('fill', 'none') // Default fill is black
.attr('stroke', 'red'); // Default color is white

return 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