Public
Edited
Apr 14, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

let line = d3.line()
.defined(([, value]) => value != null)
.x(([key, value]) => x[key](value))
.y(([key]) => y(key))
svg.append("g")
.attr("fill", "none")
.attr("stroke-width", 2)
.attr("stroke-opacity", 0.4)
.selectAll("path")
.data(data.slice().sort((a, b) => d3.ascending(a[keyz], b[keyz])))
.join("path")
.attr("stroke", d => z(d[keyz]))
.attr("d", d => line(d3.cross(keys, [d], (key, d) => [key, d[key]])))
.append("title")
.text(d => d.name);

svg.append("g")
.selectAll("g")
.data(keys)
.join("g")
.attr("transform", d => `translate(0,${y(d)})`)
.each(function(d) { d3.select(this).call(d3.axisBottom(x[d])); })
.call(g => g.append("text")
.attr("x", margin.left)
.attr("y", -6)
.attr("text-anchor", "start")
.attr("fill", "currentColor")
.text(d => d))
.call(g => g.selectAll("text")
.clone(true).lower()
.attr("fill", "none")
.attr("stroke-width", 5)
.attr("stroke-linejoin", "round")
.attr("stroke", "white"));

return svg.node();
}
Insert cell
Insert cell
Insert cell
//data = FileAttachment("cars.csv").csv({typed: true})
data = d3.csv(linkToSpreadsheet)
Insert cell
keys = data.columns
Insert cell
Insert cell
types = {
let types = {};
keys.forEach(key => types[key] = isNaN(+data[0][key]) ? "string" : "number")
return types;
}
Insert cell
Insert cell
x = {
let getXScale = (key) => types[key] === "number"
? d3.scaleLinear()
: d3.scalePoint().padding(1);
let getXdomain = (key) => types[key] === "number"
? d3.extent(data, d => d[key])
: [... new Set(data.map(m => m[key]))];
let scales = {};
keys.forEach(key => {
scales[key] = getXScale(key)
.domain(getXdomain(key))
.range([margin.top, height - margin.bottom])
})
return scales;
}
Insert cell
Insert cell
y = d3.scalePoint(keys, [margin.left, width - margin.right])
Insert cell
Insert cell
z = {
let getCScale = (key) => types[key] === "number"
? d3.scaleSequential(d3.interpolateViridis)
: d3.scaleOrdinal(d3.schemeCategory10)
return getCScale(keyz).domain(x[keyz].domain())
}
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
import {legend as Legend} from "@d3/color-legend"
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