Published
Edited
Jun 30, 2019
Importers
Insert cell
Insert cell
Insert cell
kdechart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append("g")
.attr("fill", "#127def")
.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.5)
.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, 700 - 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
x.domain()
Insert cell
bins = d3.histogram()
.domain(x.domain())
.thresholds(thresholds)
(data)
Insert cell
data = Object.assign(await d3.json("https://gist.githubusercontent.com/mbostock/4341954/raw/99757f8851178fbf60ff2173f322d1eb702d250f/faithful.json"), {title: "Time between eruptions (min.)"})
Insert cell
height = 300
Insert cell
width=800
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