Published
Edited
Dec 1, 2021
Insert cell
Insert cell
# Line Chart
Insert cell
Insert cell
chart = {
const width = 600;
const height = 300;
const margin = { top: 20, right: 20, bottom: 20, left: 30 };
const svg = d3.create("svg").attr("width", width).attr("height", height);

const x = d3
.scaleTime()
.domain(d3.extent(data, (d) => d.date))
.range([margin.left, width - margin.right]);

const y = d3
.scaleLinear()
.domain([0, d3.max(data, (d) => d3.max([d.A, d.B, d.C]))])
.range([height - margin.bottom, margin.top]);

const xAxis = d3.axisBottom(x).tickFormat(d3.timeFormat("%-m月"));
const yAxis = d3.axisLeft(y);

const lineA = d3
.line()
.x((d) => x(d.date))
.y((d) => y(d.A));
const lineB = d3
.line()
.x((d) => x(d.date))
.y((d) => y(d.B))
.curve(d3.curveNatural);
const lineC = d3
.line()
.x((d) => x(d.date))
.y((d) => y(d.C))
.curve(d3.curveStepAfter);
const items = ["A", "B", "C"];
const color = d3
.scaleOrdinal()
.domain(items)
.range(["red", "orange", "blue"]);

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

svg
.append("g")
.append("path")
.datum(data)
.attr("d", lineA)
.attr("fill", "none")
.attr("stroke", color("A"));
svg
.append("g")
.append("path")
.datum(data)
.attr("d", lineB)
.attr("fill", "none")
.attr("stroke", color("B"));
svg
.append("g")
.append("path")
.datum(data)
.attr("d", lineC)
.attr("fill", "none")
.attr("stroke", color("C"));

svg
.append("g")
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", (d) => x(d.date))
.attr("cy", (d) => y(d.A))
.attr("r", 4)
.attr("fill", color("A"));
svg
.append("g")
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", (d) => x(d.date))
.attr("cy", (d) => y(d.B))
.attr("r", 4)
.attr("fill", color("B"));
svg
.append("g")
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", (d) => x(d.date))
.attr("cy", (d) => y(d.C))
.attr("r", 4)
.attr("fill", color("C"));

svg
.append("g")
.selectAll("g")
.data(items)
.join("g")
.append("text")
.attr("x", x(data[data.length - 1].date))
.attr("y", (d) => y(data[data.length - 1][d]))
.attr("dx", 8)
.text((d) => d)
.attr("fill", color);

return svg.node();
}
Insert cell
data = (await d3.tsv(url, d3.autoType)).map((d) => ({
date: new Date(d.year, d.month - 1, d.day),
...d
}))
Insert cell
url = `https://docs.google.com/spreadsheets/d/e/2PACX-1vRgABhzZkXwZihskMCzNWKcL5lqRwyHRF-bygd7uxZ1rq7DbgcZXpSLClyh9FPJlw_JroNhDK73QUq-/pub?gid=2025566142&single=true&output=tsv`
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