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

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

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

svg
.append("path")
.attr("fill", "none")
.attr("stroke", "crimson")
.attr("d", line(values));

// svg
// .append("path")
// .attr("fill", "steelblue")
// .attr("stroke", "none")
// .attr("d", area(rawValues));

return svg.node();
}
Insert cell
function movingAverage(values, N) {
let i = 0;
let sum = 0;
const means = new Float64Array(values.length).fill(NaN);
for (let n = Math.min(N - 1, values.length); i < n; ++i) {
sum += values[i];
}
for (let n = values.length; i < n; ++i) {
sum += values[i];
means[i] = sum / N;
sum -= values[i - N + 1];
}
return means;
}
Insert cell
values = movingAverage(
bins.map((d) => d.length),
N
)
Insert cell
rawValues = movingAverage(
bins.map((d) => d.length),
1
)
Insert cell
data = d3.csvParse(await FileAttachment("chicago-homicide-dates.csv").text(), ({date}) => parseDate(date))
Insert cell
parseDate = d3.timeParse("%m/%d/%Y %I:%M:%S %p")
Insert cell
bins = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(d3.timeDay))
(data)
Insert cell
area = d3
.area()
.defined((d) => !isNaN(d))
.x((d, i) => x(bins[i].x0))
.y0(y(0))
.y1(y)
Insert cell
line = d3
.line()
.defined((d) => !isNaN(d))
.x((d, i) => x(bins[i].x0))
.y(y)
Insert cell
x = d3.scaleTime()
.domain(d3.extent(data))
.range([margin.left, width - margin.right])
Insert cell
y = d3
.scaleLinear()
.domain([0, d3.max(rawValues)])
.nice()
.rangeRound([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick line").clone()
.attr("x2", width)
.attr("stroke-opacity", 0.1))
Insert cell
height = 800
Insert cell
margin = ({top: 20, right: 12, bottom: 30, left: 30})
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