Published
Edited
Oct 31, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
dataGroup = d3.groups(desiredData, d => d.name)
Insert cell
xScale = d3.scaleTime()
.domain(d3.extent(desiredData, d => d.date)).nice()
.range([margin.left, width - margin.right])
Insert cell
xAxis = g => g
.attr("transform", `translate(0, ${height - margin.bottom})`)
.call(d3.axisBottom(xScale))
Insert cell
yScale = d3.scaleLinear()
.domain([0, d3.max(desiredData, d => d.price)]).nice()
.range([height - margin.bottom, margin.top])
Insert cell
d3.schemePastel2
Insert cell
colorScale = d3.scaleOrdinal(dataGroup.map(d => d[0]), d3.schemeSet2)
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left}, 0)`)
.call(d3.axisLeft(yScale).tickFormat(d3.format("$")))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text("Stock price"))
Insert cell
line = d3.line()
.defined(d => !isNaN(d.date))
.x(d => xScale(d.date))
.y(d => yScale(d.price))
Insert cell
chart = {
const svg = d3.create('svg')
.attr('width', width)
.attr('height', height);
svg.append('g')
.call(xAxis);
svg.append('g')
.call(yAxis);
svg.selectAll('.line')
.data(dataGroup)
.join('path')
.attr('class', 'line')
.attr('d', d => line(d[1]))
.attr('stroke', d => colorScale(d[0]))
.attr('stroke-width', 1)
.attr('fill', 'none');
let legend = svg.selectAll(".legend")
.data(dataGroup)
.enter();
legend
.append('text')
.text(d => d[0])
.attr('x', legendOrigin[0] + labelHeight * 1.2)
.attr('y', (d,i) => legendOrigin[1] + labelHeight + labelHeight * 1.2 *i)
.style('font-family', 'sans-serif')
.style('font-size', `${labelHeight-3}px`);
legend
.append('rect')
.attr('x', legendOrigin[0])
.attr('y', (d,i) => legendOrigin[1] + labelHeight * 1.2 * i)
.attr('width', labelHeight)
.attr('height', labelHeight)
.attr('fill', d => colorScale(d[0]))
.attr('stroke', 'none');
return svg.node();
}
Insert cell
Insert cell
legendOrigin = [width - margin.right - 35, height/2 - 40]
Insert cell
labelHeight = 15;
Insert cell
height = 400
Insert cell
width = 800
Insert cell
margin = ({top: 25, right: 25, bottom: 35, left: 50})
Insert cell
d3 = require("d3@^6.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