Published
Edited
Sep 27, 2019
Importers
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);

const strokeWidth = data.series.length > 10 ? 1.5 : 3,
opacity = data.series.length > 10 ? .2 : .7;

const path = svg
.append("g")
.attr("fill", "none")
.selectAll("path")
.data(data.series)
.join("path")
.attr("stroke", d => {
return typeof d.color !== 'undefined' ? d.color : 'steelblue';
})
.attr("stroke-width", strokeWidth)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.style("mix-blend-mode", "multiply")
.style("opacity", opacity)
.attr("d", d => line(d.values));

return svg.node();
}
Insert cell
height = 600
Insert cell
margin = ({top: 20, right: 20, bottom: 30, left: 30})
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data.dates))
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([d3.min(data.series, d => d3.min(d.values)), d3.max(data.series, d => d3.max(d.values))]).nice()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80).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.select(".tick:last-of-type text").clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
Insert cell
line = d3.line()
.defined(d => !isNaN(d))
.x((d, i) => x(data.dates[i]))
.y(d => y(d))
Insert cell
data = {
const data = await d3.tsv("https://gist.githubusercontent.com/mbostock/8033015/raw/01e8225d4a65aca6c759fe4b8c77179f446c5815/unemployment.tsv", (d, i, columns) => {
return {
name: d.name.replace(/, ([\w-]+).*/, " $1"),
values: columns.slice(1).map(k => +d[k])
};
});
return {
y: "% Unemployment",
series: data,
dates: data.columns.slice(1).map(d3.utcParse("%Y-%m"))
};
}
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