Published
Edited
Nov 18, 2020
1 star
Insert cell
md`# D3 Line Chart`
Insert cell
data = {
const allData = (d3.csvParse(await FileAttachment("big-mac-raw-index.csv").text(), d3.autoType))
.map(({ date, name, dollar_price, iso_a3 }) => ({ name, iso: iso_a3, date: new Date(date), price: dollar_price }))

return [
allData.filter(({ iso }) => iso === 'USA'),
allData.filter(({ iso }) => iso === 'CAN'),
allData.filter(({ iso }) => iso === 'CHN'),
allData.filter(({ iso }) => iso === 'EUZ'),
allData.filter(({ iso }) => iso === 'JPN')
]

}
Insert cell
width = 900
Insert cell
height = 500
Insert cell
Insert cell
colors = {
const countryNames = data.map(d => d[0].name)
return d3.scaleOrdinal(
countryNames,
d3.schemeCategory10
)
}
Insert cell
xScale = {
const startDate = data[0][0].date,
endDate = data[0][data[0].length - 1].date
return d3.scaleTime(
// domain
[ startDate, endDate ],
// range
[ margin.left, width - margin.right ]
)
}
Insert cell
yScale = {
// flatten the data into a single array
const prices = data.flat().map(d => d.price),
// and find the max value from that array
yMax = d3.max( prices )
return d3.scaleLinear(
[ 0, yMax ],
[ height - margin.bottom, margin.top ]
)
}
Insert cell
yAxis = {
const formatter = d3.format('$.2f')
return d3.axisLeft(yScale)
.tickFormat(d => formatter(d))
}
Insert cell
Insert cell
line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price))
.curve(d3.curveNatural)
Insert cell
xAxis = d3.axisBottom(xScale)
Insert cell
d3 = require('d3@5')
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more