Published
Edited
Oct 27, 2020
Insert cell
Insert cell
Insert cell
Insert cell
reveal = path => path.transition()
.duration(5000)
.ease(d3.easeLinear)
.attrTween("stroke-dasharray", function() {
const length = this.getTotalLength();
return d3.interpolate(`0,${length}`, `${length},${length}`);
})
Insert cell
viewof t = Scrubber(d3.ticks(0, 1, 200), {
autoplay: false,
loop: false,
initial: 50,
format: x => `t = ${x.toFixed(3)}`
})
Insert cell
html`<svg viewBox="0 0 ${width} ${height}">
<path d="${line(data)}" fill="none" stroke="steelblue" stroke-width="1.5" stroke-miterlimit="1" stroke-dasharray="${lineLength * t},${lineLength}"></path>
${d3.select(svg`<g>`).call(xAxis).node()}
${d3.select(svg`<g>`).call(yAxis).node()}
</svg>`
Insert cell
lineLength = svg`<path d="${line(data)}">`.getTotalLength()
Insert cell
viewof replay2 = html`<button>Replay`
Insert cell
{
replay2;
for (let i = 0, n = 300; i < n; ++i) {
yield i;
}
}
Insert cell
{
replay2;

const path = svg`<path d="${line(data)}" fill="none" stroke="steelblue" stroke-width="1.5" stroke-miterlimit="1">`;

const chart = html`<svg viewBox="0 0 ${width} ${height}">
${path}
${d3.select(svg`<g>`).call(xAxis).node()}
${d3.select(svg`<g>`).call(yAxis).node()}
</svg>`;

for (let i = 0, n = 300; i < n; ++i) {
const t = (i + 1) / n;
path.setAttribute("stroke-dasharray", `${t * lineLength},${lineLength}`);
yield chart;
}
}
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

const zx = x.copy(); // x, but with a new domain.

const line = d3.line()
.x(d => zx(d.date))
.y(d => y(d.close));

const path = svg.append("path")
.attr("fill", "none")
.attr("stroke", "#5ba872")
.attr("stroke-width", 1.5)
.attr("stroke-miterlimit", 1)
.attr("d", line(data));

const gx = svg.append("g")
.call(xAxis, zx);

const gy = svg.append("g")
.call(yAxis, y);

return Object.assign(svg.node(), {
update(domain) {
const t = svg.transition().duration(750);
zx.domain(domain);
gx.transition(t).call(xAxis, zx);
path.transition(t).attr("d", line(data));
}
});
}
Insert cell
Insert cell
data = d3.csvParse(await FileAttachment("TSLA (1).csv").text(), d3.autoType).map(
d => ({
...d,
close: +d.Close,
date: new Date(d.Date)
}))
Insert cell
// formatDate = d3.timeFormat('%Y-%m-%d') // makes it string
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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