Published
Edited
Apr 30, 2020
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
data = {
const csv = await d3.csv(
'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv', d3.autoType)
const statesMap = new Map() // help look up the series for each state
const datesSet = new Set() // store all the dates
const series = []; // a collection of all the series [{state, values: [{date, cases} ...]} ...]
csv.forEach(({date, state, cases}) => {
datesSet.add(date)
if (!statesMap.has(state)) {
statesMap.set(state, series.length)
series.push({state, values: []})
}
series[statesMap.get(state)].values.push({date, cases})
})
return {
series,
dates: Array.from(datesSet),
states: ['All', ...Array.from(statesMap.keys()).sort()],
statesMap,
}
}
Insert cell
Insert cell
Insert cell
xScale = d3.scaleUtc()
.domain(d3.extent(data.dates)).nice()
.range([margin.left, width - margin.right])
Insert cell
Insert cell
yScale = {
const scale = d3.scaleLinear().range([height - margin.bottom, margin.top])
if (selectedState === 'All') {
scale.domain([0, d3.max(data.series, (s) => d3.max(s.values, (d) => d.cases))]).nice()
} else {
const slice = data.series[data.statesMap.get(selectedState)]
scale.domain([0, d3.max(slice.values, (d) => d.cases)]).nice()
}
return scale
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
color = d3.schemeCategory10
Insert cell
Insert cell
Insert cell
Insert cell
{
const svg = d3.select(DOM.svg(width, height))
svg.append('g').call(title('Coronavirus (Covid-19) Total Cases of Each State in the US'))
// Draw the x and y axes.
svg.append('g').call(xAxis('Date'))
svg.append('g').call(yAxis('Cases'))
// Draw the grid lines.
svg.append('g').call(xGrid)
svg.append('g').call(yGrid)
// Draw the lines.
svg.append('g')
.selectAll('path')
.data(data.series)
.join('path')
.attr('d', (d) => line(d.values))
.style('stroke', (d, i) => color[i % 10])
.style('opacity', (d) => (selectedState === 'All' || selectedState === d.state) ? 1 : 0)
return svg.node()
}
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