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

svg.append("g")
.attr("fill", "#bbb")
.selectAll("rect")
.data(bins)
.join("rect")
.attr("x", d => x(d.x0) + 1)
.attr("y", d => y(d.length / data.length))
.attr("width", d => x(d.x1) - x(d.x0) - 1)
.attr("height", d => y(0) - y(d.length / data.length));

svg.append("path")
.datum(density)
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-width", 1)
.attr("stroke-linejoin", "round")
.attr("d", line);

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

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

return svg.node();
}
Insert cell
function kde(kernel, thresholds, data) {
return thresholds.map(t => [t, d3.mean(data, d => kernel(t - d))]);
}
Insert cell
function epanechnikov(bandwidth) {
return x => Math.abs(x /= bandwidth) <= 1 ? 0.75 * (1 - x * x) / bandwidth : 0;
}
Insert cell
line = d3.line()
.curve(d3.curveBasis)
.x(d => x(d[0]))
.y(d => y(d[1]))
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data)).nice()
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(bins, d => d.length) / data.length])
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
.call(g => g.append("text")
.attr("x", width - margin.right)
.attr("y", -6)
.attr("fill", "#000")
.attr("text-anchor", "end")
// .attr("font-weight", "bold")
.text(data.title))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(null, "%"))
.call(g => g.select(".domain").remove())
Insert cell
thresholds = x.ticks(40)
Insert cell
density = kde(epanechnikov(bandwidth), thresholds, data)
Insert cell
bins = d3.bin()
.domain(x.domain())
.thresholds(thresholds)
(data)
Insert cell
data = Object.assign(await FileAttachment("new@12.json").json())
Insert cell
height = 80
Insert cell
width = 150
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 40})
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