Published
Edited
Jan 15, 2021
1 fork
Importers
1 star
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append("g")
.attr("fill", "steelblue")
.attr("fill-opacity", 0.8)
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => x(d.xAxis))
.attr("width", x.bandwidth())
.attr("y", d => y1(d.bar))
.attr("height", d => y1(0) - y1(d.bar));

svg.append("path")
.attr("fill", "none")
.attr("stroke", "currentColor")
.attr("stroke-miterlimit", 1)
.attr("stroke-width", 3)
.attr("d", line(data));

svg.append("g")
.attr("fill", "none")
.attr("pointer-events", "all")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => x(d.xAxis))
.attr("width", x.bandwidth())
.attr("y", 0)
.attr("height", height)
.append("title")
.text(d => `${d.xAxis}:
${data.y1}: ${d.bar.toLocaleString("en")}
${data.y2}: ${d.line.toLocaleString("en")}`);

svg.append("g")
.call(xAxis);

svg.append("g")
.call(y1Axis);

svg.append("g")
.call(y2Axis);

return svg.node();
}
Insert cell
data = Object.assign(d3.csvParse(await FileAttachment("new-passenger-cars.csv").text(), d3.autoType).map(o => ({xAxis: o.year, bar:o.sales, line:o.efficiency})), {y1: " New cars sold", y2: "Avg. fuel efficiency (mpg)"})
Insert cell
line = d3.line()
.x(d => x(d.xAxis) + x.bandwidth() / 2)
.y(d => y2(d.line))
Insert cell
x = d3.scaleBand()
.domain(data.map(d => d.xAxis))
.rangeRound([margin.left, width - margin.right])
.padding(0.1)
Insert cell
y1 = d3.scaleLinear()
.domain([0, d3.max(data, d => d.bar)])
.rangeRound([height - margin.bottom, margin.top])
Insert cell
y2 = d3.scaleLinear()
.domain(d3.extent(data, d => d.line))
.rangeRound([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x)
.tickValues(d3.ticks(...d3.extent(x.domain()), width / 40).filter(v => x(v) !== undefined))
.tickSizeOuter(0))
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(data.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(data.y2))
Insert cell
height = 500
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 40})
Insert cell
d3 = require("d3@6")
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