Published
Edited
May 20, 2020
1 fork
2 stars
Insert cell
md`# Animated line chart`
Insert cell
chart ={
let w = width;
let h = 752 * w / 1260;
const svg = d3.select(DOM.svg(w, h))

let margin = {top: 30, right: 20, bottom: 35, left: 20};

let xScale = d3.scaleTime()
.range([margin.left, w])
.domain([1990, 2050]);

let yScale = d3.scaleLinear()
.range([h, 0])
.domain([6, 8.5])
//.interpolate(d3.interpolateRound);

let line = d3.line()
.x( d => xScale(d.year))
.y( d =>yScale(d.observation))
const formatYears = d3.timeFormat("%Y");
let xaxis = svg.append("g")
.attr("transform", "translate(0," + (h + 5) + ")")
.attr("class", "x axis")
.call(
d3.axisBottom(xScale)
.tickSizeInner(-h - 5)
.tickFormat(formatYears)
)
.selectAll("text")
.attr('y', 5);
let yaxis = svg.append("g")
.attr("class", "y axis")
.call(
d3.axisLeft(yScale)
.ticks(5)
.tickSizeInner(-w)
)
.selectAll("text")
.style("text-anchor", "start")
.attr('x', 0)
.attr('y', -10);
svg.append("path")
.datum(data)
.attr("d", line)
.attr('class', 'temperature-line')
.call(transition);

return svg.node();
}
Insert cell
function transition(path) {
path.transition()
.duration(2000)
.attrTween("stroke-dasharray", tweenDash)
.on("end", () => { d3.select('.temperature-line').call(transition); });
}

Insert cell
html`<style>

.temperature-line{
fill:none;
stroke:#c70000;
stroke-width:2px;
}

</style>`
Insert cell
function tweenDash() {
const l = this.getTotalLength(),
i = d3.interpolateString("0," + l, l + "," + l);
return function(t) { return i(t) };
}
Insert cell
data = d3.csvParse(dataRaw, d3.autoType)
Insert cell
dataRaw = FileAttachment("uk.csv").text()
Insert cell
d3 = require('d3@5')
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