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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more