Published
Edited
Aug 12, 2020
Insert cell
Insert cell
chart = {
const root = d3.create("div")
.attr("class", "root");
const svg = root.append("svg")
.attr("viewBox", [0, 0, width, height])
.style("overflow", "visible");

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

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

const path = svg
.append("g")
.attr("fill", "none")
.attr("stroke-width", 3)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.selectAll("path")
.data(data.series)
.join("path")
.style("mix-blend-mode", "multiply")
.attr("d", d => line(d.values));

path.attr("stroke", d => color(d.name));
svg.call(hover, path);
svg.append("g")
.call(legend);
window.addEventListener("resize", () => resized(width, root, svg));
setTimeout(() => resized(width, root, svg), 12);
return root.node();
}
Insert cell
legend = svg => {
const g = svg
.attr("transform", `translate(${width},0)`)
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g")
.data(color.domain().slice().reverse())
.join("g")
.attr("transform", (d, i) => `translate(0,${i * 20})`);

g.append("rect")
.attr("x", -19)
.attr("width", 15)
.attr("height", 15)
.attr("fill", color);

g.append("text")
.attr("x", -28)
.attr("y", 9.5)
.attr("dy", "0.35em")
.text(d => d);
}
Insert cell
function resized(width, root, svg) {
let measuredWidth = root.node().getBoundingClientRect().width;
if (measuredWidth == 0) {
setTimeout(() => resized(width, root, svg), 12);
return;
}
let scale = width / measuredWidth;
svg.selectAll("line").attr("stroke-width", scale + "px");
svg.selectAll("text").attr("transform", "scale(" + scale + " " + scale + ")");
}
Insert cell
data = {
const data = await d3.csv(
"https://raw.githubusercontent.com/prayaggordy/D3-covid-map/master/data/hospit_data.csv"
);
const columns = data.columns.slice(1);
return {
y: "Number of beds",
series: data.map(d => ({
name: d.name.replace(/, ([\w-]+).*/, " $1"),
values: columns.map(k => +d[k])
})),
dates: columns.map(d3.utcParse("%Y-%m-%d"))
};
}
Insert cell
color = d3
.scaleOrdinal()
.domain(["Total", "Acute", "ICU"])
.range(['#AE76A6', '#cf7d94', '#A3C3D9'])
Insert cell
function hover(b, path) {
if ("ontouchstart" in document)
b
.style("-webkit-tap-highlight-color", "transparent")
.on("touchmove", moved)
.on("touchstart", entered)
.on("touchend", left);
else
b
.on("mousemove", moved)
.on("mouseenter", entered)
.on("mouseleave", left);

const dot = b.append("g").attr("display", "none");

dot.append("circle")
.datum(data)
.attr("r", 3);

dot
.append("rect")
.attr("width", 100)
.attr("height", 30)
.attr("fill", "white")
.attr("y", -37)
.attr("x", -50)
.attr("stroke", "lightgrey");

dot
.append("text")
.attr("font-family", "Helvetica")
.attr("font-size", 11)
.attr("text-anchor", "middle")
.attr("y", -18)
.raise();

const formatTime = d3.timeFormat("%B %d");

function moved() {
d3.event.preventDefault();
const mouse = d3.mouse(this);
const xm = x.invert(mouse[0]);
const ym = y.invert(mouse[1]);
const i1 = d3.bisectLeft(data.dates, xm, 1);
const i0 = i1 - 1;
const i = xm - data.dates[i0] > data.dates[i1] - xm ? i1 : i0;
const s = d3.least(data.series, d => Math.abs(d.values[i] - ym));
path
.attr("stroke", d => (d === s ? color(s.name) : "#ddd"))
.filter(d => d === s)
.raise();
dot.attr("transform", `translate(${x(data.dates[i])},${y(s.values[i])})`);
dot
.select("circle")
.attr("fill", color(s.name));
let node = dot.select("text").node();
node.innerHTML = "";
node.appendChild(svg`
<tspan><tspan font-weight = "bold">${s.name}:</tspan> ${s.values[i]} beds in use (${formatTime(data.dates[i])}) </tspan>`
);
dot
.select("rect")
.attr(
"x",
-dot
.select("text")
.node()
.getComputedTextLength() / 2 - 10
)
.attr(
"width",
dot
.select("text")
.node()
.getComputedTextLength() + 20
);
dot.select("text").raise();
}

function entered() {
// path.style("mix-blend-mode", null).attr("stroke", "#ddd");
dot.attr("display", null);
}

function left() {
path.style("mix-blend-mode", "multiply").attr("stroke", d => color(d.name));
dot.attr("display", "none");
}
}
Insert cell
height = 200
Insert cell
width = 550
Insert cell
margin = ({ top: 20, right: 10, bottom: 20, left: 0 })
Insert cell
x = d3.scaleUtc()
.domain(d3.extent(data.dates))
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([0, 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 / 120).tickSize(0))
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisRight(y)
.ticks(height / 50, data.format)
.tickSize(0))
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick:not(:first-of-type) line")
.attr("stroke-dasharray", "2,2")
.attr("stroke-opacity", d => d === 1 ? null : 0.25)
.attr("x2", width - margin.left - margin.right))
.call(g => g.selectAll(".tick text")
.attr("x", 4)
.attr("dy", -4))
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 44)
.attr("text-anchor", "start")
.text(" " + "beds"))
.call(g => g.select(".tick:first-of-type text").remove())
Insert cell
line = d3.line()
.defined(d => !isNaN(d))
.x((d, i) => x(data.dates[i]))
.y(d => y(d))
Insert cell
d3 = require("d3@5", "d3-array@2")
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