Published
Edited
Aug 13, 2020
7 forks
3 stars
Insert cell
Insert cell
Insert cell
barWidth = xBand.bandwidth()
Insert cell
barXPosition = d => xTime(d.year) - barWidth/2
Insert cell
lineXPosition = d => xTime(d.year)
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(xTime)
.tickSizeOuter(0))
Insert cell
xTime = d3.scaleTime()
.domain(paddedExtent)
.rangeRound([margin.left, width - margin.right])
Insert cell
xBand = d3.scaleBand()
.domain(d3.timeYear.range(...xTime.domain()))
.rangeRound([margin.left, width - margin.right])
.padding(0.1)
Insert cell
// add one time unit of padding to make sure bars don't overlap with y-axis
paddedExtent = [
d3.min(dateData.map(d => d3.timeYear.offset(d.year, -1))),
d3.max(dateData.map(d => d3.timeYear.offset(d.year, 1)))
];
Insert cell
Insert cell
Insert cell
origData = Object.assign(d3.csvParse(await FileAttachment("new-passenger-cars.csv").text(), d3.autoType), {y1: "↑ New cars sold", y2: "Avg. fuel efficiency (mpg) ↑"})
Insert cell
dateData = origData.map(d => ({...d, year: new Date(d.year, 0, 1)}))
Insert cell
line = d3.line()
.x(lineXPosition)
.y(d => y2(d.efficiency))
Insert cell
y1 = d3.scaleLinear()
.domain([0, d3.max(dateData, d => d.sales)])
.rangeRound([height - margin.bottom, margin.top])
Insert cell
y2 = d3.scaleLinear()
.domain(d3.extent(dateData, d => d.efficiency))
.rangeRound([height - margin.bottom, margin.top])
Insert cell
y1Axis = g => g
.attr("transform", `translate(${margin.left},0)`)
.style("color", "steelblue")
.call(d3.axisLeft(y1).ticks(null, "s"))
.call(g => g.select(".domain").remove())
.call(g => g.append("text")
.attr("x", -margin.left)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text(origData.y1))
Insert cell
y2Axis = g => g
.attr("transform", `translate(${width - margin.right},0)`)
.call(d3.axisRight(y2))
.call(g => g.select(".domain").remove())
.call(g => g.append("text")
.attr("x", margin.right)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "end")
.text(origData.y2))
Insert cell
height = 500
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 40})
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