Published
Edited
Nov 18, 2019
Insert cell
Insert cell
chart = {
const svg = d3.create('svg')
.attr('viewBox', "0 0 500 1000");
svg.selectAll('.bar')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('y', d => yScale(d.key))
.attr('height', yScale.bandwidth())
.attr('fill', d => {
if (d.key == "Game of Thrones") return 'darkred';
return (d.value.difference > 0) ? 'green' : 'crimson';
})
.attr('x', xScale(0))
.attr('width', 0)
.transition()
.duration(1500)
.ease(d3.easeCubic)
.attr('x', d => xScale(Math.min(d.value.difference, 0)))
.attr('width', d => Math.abs(xScale(0) - xScale(d.value.difference)));
svg.selectAll('.title')
.data(data)
.enter().append('text')
.attr('class', 'title')
.attr('x', d => xScale((d.value.difference > 0) ? -0.02 : 0.02))
.attr('y', d => yScale(d.key) + yScale.bandwidth()/2)
.attr('text-anchor', d => d.value.difference > 0 ? 'end' : 'start')
.attr('dominant-baseline', 'middle')
.attr('fill', 'black')
.text(d => {
if (d.key == "Lost - Les disparus") return "Lost";
if (d.key == "How I Met Your Mother") return "HIMYM";
return d.key;
})
.style('font-size', `${yScale.bandwidth() - 12}px`)
.style('opacity', 0);
svg.selectAll('.title').each(function(d, i) {
d3.select(this)
.transition()
.duration(500)
.delay(1500 + i * 50)
.style('opacity', 1);
});

return svg.node();
}
Insert cell
yScale = d3.scaleBand()
.domain(data.map(d => d.key))
.range([50, 950])
.padding(0.1);
Insert cell
xScale = d3.scaleLinear()
.domain([-0.7, 0.2])
.range([50, 450]);
Insert cell
data = {
let data = d3.nest()
.key(d => d.title)
.rollup(v => {
let mean = d3.mean(v, d => +d.rating);
let max = d3.max(v, d => +d.rating);
let finale = v[v.length - 1];
return {
averageRating: mean,
finaleRating: +finale.rating,
difference: (+finale.rating - mean) / mean,
finaleTitle: finale.episode,
finaleAirdate: finale.airdate,
max: max
};
})
.entries(rawData);
data = data.filter(function(d) {
return Math.abs(d.value.difference) > 0.02;
});
data.sort(function(a, b) {
return a.value.difference - b.value.difference;
});
return data;
}
Insert cell
rawData = d3.tsv("https://raw.githubusercontent.com/TomFevrier/tv-finales/master/episodes.tsv");
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