Published
Edited
Oct 19, 2021
Insert cell
Insert cell
Insert cell
rawData = FileAttachment("asia.csv").csv()
Insert cell
Insert cell
dayTemps = rawData.map((cityDay) => ({
temperature:
cityDay.AvgTemperature == -99
? undefined
: parseFloat(cityDay.AvgTemperature),
city: cityDay.City,
country: cityDay.Country,
dateObj: new Date(
parseInt(cityDay.Year),
parseInt(cityDay.Month) - 1,
parseInt(cityDay.Day)
)
}))
Insert cell
Insert cell
cities = groupBy(
dayTemps.filter((d) => d.temperature),
"city"
)
Insert cell
groupBy = (items, key) =>
items.reduce(
(result, item) => ({
...result,
[item[key]]: [...(result[item[key]] || []), item]
}),
{}
)
Insert cell
Insert cell
preparedData = Object.values(cities)
Insert cell
Insert cell
flatTemps = Object.values(cities)
.map((city) => city.map((day) => day.temperature))
//remove by-city sorting
.flat()
//remove undefineds
.filter((d) => d)
Insert cell
flatDates = Object.values(cities)
.map((city) => city.map((day) => day.dateObj))
//remove by city sorting
.flat()
//remove undefined
.filter((d) => d)
Insert cell
Insert cell
height = 400
Insert cell
margin = ({ top: 20, right: 20, bottom: 30, left: 60 })
Insert cell
xScale = d3
.scaleTime()
.domain(d3.extent(flatDates))
.range([margin.left, width - margin.right])
Insert cell
xAxis = (g) =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(xScale))
Insert cell
yScale = d3
.scaleLinear()
.domain(d3.extent(flatTemps))
.nice()
.range([height - margin.bottom, margin.top])
Insert cell
yAxis = (g) =>
g.attr("transform", `translate(${margin.left},0)`).call(d3.axisLeft(yScale))
Insert cell
md`-----
### Line Generator
`
Insert cell
line = d3
.line()
.x((d) => xScale(d.dateObj))
.y((d) => yScale(d.temperature))
//.curve(d3.curveBasis)
Insert cell
Insert cell
{
// Create an empty SVG with specified width and height.
const svg = d3.create("svg").attr("width", width).attr("height", height);
svg
.append("rect")
.attr("width", width)
.attr("height", height)
.attr("fill", "#999");

// Draw the x and y axes.
svg.append("g").call(xAxis);
svg.append("g").call(yAxis);

// Draw the line.
svg
.selectAll(".stateLines")
.data(preparedData)
.enter()
.append("path")
.attr("d", (d) => line(d))
.attr("fill", "none")
.attr("stroke", "white")
.attr("stroke-width", 0.1)
.on("mouseover", (e, d) => console.log(d[0].city));

return svg.node();
}
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