Published
Edited
Aug 9, 2022
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
parseTime = d3.timeParse("%Y-%m-%d")
Insert cell
data = {
const out = [];
for (let e of sandbox) {
const { date, added, updated, deleted } = e;
out.push({
date: parseTime(date),
value: Number(deleted),
key: "deleted"
});

out.push({
date: parseTime(date),
value: Number(updated),
key: "updated"
});

out.push({
date: parseTime(date),
value: Number(added),
key: "added"
});
}
return out;
}
Insert cell
Insert cell
Insert cell
grouped = d3.group(data, (d) => d.key)
Insert cell
Insert cell
yExtent = d3.extent(data, (d) => d.value)
Insert cell
xExtent = d3.extent(data, (d) => d.date)
Insert cell
xScale = d3
.scaleTime()
.domain(xExtent)
.range([margin.left, width - margin.right])
Insert cell
yScale = d3
.scaleLinear()
.domain([0, yExtent[1] + 3]) // + 3 leaves some buffer
.range([height - margin.bottom, margin.top])
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
//draw xAxis and xAxis label
chart = {
const xAxis = d3
.axisBottom()
.scale(xScale)
.tickFormat(d3.timeFormat("%Y-%m-%d"));

// you'll want to replace this with
// const svg = select(svgRef.current) in React.
const svg = d3.select(DOM.svg(width, height));

svg
.append("g")
.attr("class", "axis")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(xAxis);

//yAxis and yAxis label
const yAxis = d3.axisLeft().scale(yScale);

svg
.append("g")
.attr("class", "axis")
.attr("transform", `translate(${margin.left},0)`)
.call(yAxis);

const colors = {
added: "green",
updated: "orange",
deleted: "purple"
};

svg
.selectAll(".line")
.append("g")
.attr("class", "line")
.data(grouped)
.enter()
.append("path")
// d will be each entry in grouped.
.attr("d", function (d) {
// key will be either "updated", "deleted", "added"
// values will be the array of [{date: __, key: __, value: }, ...] associated with key
const [key, values] = d;
return d3
.line()
.x((d) => xScale(d.date))
.y((d) => yScale(d.value))(values);
})
.attr("fill", "none")
.attr("stroke", (d) => colors[d[0]])
.attr("stroke-width", 2);

return svg.node();
}
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