Public
Edited
Jun 25, 2021
Insert cell
md`# D3 Line/Area Chart using datum`
Insert cell
Insert cell
{
const margin = {top: 40, right: 40, bottom: 50, left: 50},
fontFamily = "helvetica",
width = 500-margin.left-margin.right,
height = 500-margin.top-margin.bottom,
numPoints = 20,
maxVal = 50,
svg = d3.create("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style("background-color", svgBackgroundColor),
lineChart = svg
.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"),
points = d3.range(numPoints).map(d => {
return {
x: d,
y: Math.floor(Math.random() * maxVal)
}
}),
x = d3.scaleLinear()
.range([0,width])
.domain([0,numPoints-1]),
y = d3.scaleLinear()
.range([height,0])
.domain([0,maxVal])

let xAxis = lineChart.append('g')
.classed('axis--x', true)
.call(d3.axisBottom(x))
.attr("transform", `translate(0,${height})`);
let yAxis = lineChart.append('g')
.classed('axis--y', true)
.call(d3.axisLeft(y));
//chart line
lineChart.append("path")
.datum(points)
.attr("fill", "none")
.attr("stroke", lineStrokeColor)
.attr("stroke-width", 1.5)
.attr("d", d3.line()
.x(d => x(d.x))
.y(d => y(d.y)));
//add circles to each point on the line
lineChart.selectAll("circle")
.data(points)
.join('circle')
.attr("fill", lineStrokeColor)
.attr('r', 2)
.attr('cx', d => x(d.x))
.attr('cy', d => y(d.y));
//fill in the area under the line
//docs: https://github.com/d3/d3-shape#areas
lineChart.append("path")
.datum(points)
.attr("class", "area")
.attr("d", d3.area()
.x(d => x(d.x))
.y0(height)
.y1(d => y(d.y)))
.style("fill", fillColor)
.style('opacity', fillOpacity);
yield svg.node();
}

Insert cell
svgBackgroundColor = "#152c33"
Insert cell
fillColor = "#adb5bd"
Insert cell
lineStrokeColor = '#bfd200'
Insert cell
fillOpacity = 0.1
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