Published
Edited
Apr 18, 2021
1 star
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
_ = require('lodash')
Insert cell
height = 600
Insert cell

width = 400
Insert cell
margin = ({top: 30, right: 30, bottom: 20, left: 50})
Insert cell
url = 'https://gist.githubusercontent.com/javier1nc/be60c4bbe674cb3e98b859096af4dfe4/raw/c69ca0ad687435030fffdac771089377ed172fa8/aapl.json';
Insert cell

data=d3.json(url).then(data => _.values(data.map(({date, close}) => ({date: new Date(date), value: +close}))));
Insert cell
x = d3.scaleLinear()
.domain([d3.max(data, d => d.value), 0]).nice()
.range([width - margin.right, margin.left])
Insert cell
y = d3.scaleUtc()
.domain(d3.extent(data, d => d.date))
.range([margin.top, height - margin.bottom])
Insert cell
width
Insert cell
line = d3.line()
.defined(d => !isNaN(d.value))
.x(d => x(d.value))
.y(d => y(d.date))
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);

svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("d", line);

return svg.node();
}
Insert cell
xAxis = g => g
.attr("transform", `translate(${0},${margin.top})`)
.call(d3.axisTop(x).ticks(width / 80).tickSizeOuter(0))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(height / 60).tickSizeOuter(0))
// .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(data.y))
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