Published
Edited
Mar 23, 2020
Insert cell
Insert cell
Insert cell
Insert cell
height = 600
Insert cell
margin = ({top: 20, right: 40, bottom: 30, left: 40})
Insert cell
x = d3.scaleUtc()
.domain(d3.extent(data, d => d.date))
.range([margin.left, width - margin.right])
.clamp(true)
Insert cell
y = d3.scaleLog()
.domain([1 / k, k])
.rangeRound([height - margin.bottom, margin.top])
Insert cell
k = d3.max(d3.group(data, d => d.name), ([, group]) => d3.max(group, d => d.value) / d3.min(group, d => d.value))
Insert cell
z = d3.scaleOrdinal(d3.schemeCategory10).domain(data.map(d => d.name))
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y)
.ticks(null, x => +x.toFixed(6) + "×"))
.call(g => g.selectAll(".tick line").clone()
.attr("stroke-opacity", d => d === 1 ? null : 0.2)
.attr("x2", width - margin.left - margin.right))
.call(g => g.select(".domain").remove())
Insert cell
parseDate = d3.utcParse("%Y-%m-%d")
Insert cell
formatDate = d3.utcFormat("%B, %Y")
Insert cell
line = d3.line()
.x(d => x(d.date))
.y(d => y(d.value))
Insert cell
bisect = d3.bisector(d => d.date).left
Insert cell
series = d3.groups(data, d => d.name).map(([key, values]) => {
const v = values[0].value;
return {key, values: values.map(({date, value}) => ({date, value: value / v}))};
})
Insert cell
data = d3.merge(await Promise.all([FileAttachment("AAPL.csv"), FileAttachment("AMZN.csv"), FileAttachment("GOOG.csv"), FileAttachment("IBM.csv"), FileAttachment("MSFT.csv")].map(async file => d3.csvParse(await file.text(), d => {
const date = parseDate(d["Date"]);
return {name: file.name.slice(0, -4), date, value: +d["Close"]};
}))))
Insert cell
d3 = require("d3@5", "d3-array@2")
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