Published
Edited
Jun 10, 2020
1 fork
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("overflow", "visible");

svg.append("g")
.call(xAxis)
.selectAll('text')
.attr("color", "gray")
.attr('font-size',18)

svg.append("g")
.call(yAxis)
.selectAll('text')
.attr("color", "gray")
.attr('font-size',18);

const gradient = DOM.uid();
svg.append("linearGradient")
.attr("id", gradient.id)
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", height)
.selectAll("stop")
.data([
{offset: 0, color: "red"},
{offset: 1, color: "steelblue"}
])
.join("stop")
.attr("offset", d => d.offset)
.attr("stop-color", d => d.color);
const path = svg.append("g")
.attr("fill", "none")
.attr("stroke", gradient)
.attr("stroke-width", 5)
.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));

svg.call(hover, path);

return svg.node();
}
Insert cell
data_raw = {
//const data = d3.csvParse(await FileAttachment("brazil_mobility@2.csv").text());
const data = await d3.csv("https://hackcovid.s3-us-west-2.amazonaws.com/data/data_mobility.csv", d3.autoType)
const columns = data.columns.slice(2);
return {
series: data.map(d => ({
name: d.sub_region_1.replace(/, ([\w-]+).*/, " $1"),
type: d.local.replace(/, ([\w-]+).*/, " $1"),
values: columns.map(k => +d[k])
})),
dates: columns.map(d3.utcParse("%Y-%m-%d"))
};
}
Insert cell
state = "DF"
Insert cell
data = {
const series = data_raw.series.filter(d => d.name === state);
const dates = data_raw.dates;
const type = data_raw.type;
return {
series,
dates
}
}
Insert cell
function hover(svg, path) {
if ("ontouchstart" in document) svg
.style("-webkit-tap-highlight-color", "transparent")
.on("touchmove", moved)
.on("touchstart", entered)
.on("touchend", left)
else svg
.on("mousemove", moved)
.on("mouseenter", entered)
.on("mouseleave", left);

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

dot.append("circle")
.attr("r", 2.5);

const dotTextDate = dot.append("text")
.attr("font-family", "sans-serif")
.attr("font-size", 18)
.attr("text-anchor", "middle")
.attr("y", -8);
const dotTextValue = dot.append("text")
.attr("font-family", "sans-serif")
.attr("font-size", 18)
.attr("text-anchor", "middle")
.attr("y", 8);

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 ? null : "#ddd").filter(d => d === s).raise();
dot.attr("transform", `translate(${x(data.dates[i])},${y(s.values[i])})`);
dotTextDate
.text(`${formatTime(data.dates[i])}`);
dotTextValue
.text(`${s.values[i]}%`)
d3.select("#mobility-title").text(s.type);
}

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", null);
dot.attr("display", "none");
d3.select("#mobility-title").text("");
}
}
Insert cell
formatTime = d3.utcFormat("%d/%m/%y");
Insert cell
height = 600
Insert cell
width = 600
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 55})
Insert cell
x = d3.scaleUtc()
.domain(d3.extent(data.dates))
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([-100, 100]).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).tickSizeOuter(0))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickFormat(d => `${d}%`))
.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")
.attr("id", "mobility-title")
.text(""))
.call(g => g.selectAll(".tick line")
.select(function() { return this.parentNode.appendChild(this.cloneNode()); })
.attr("stroke-opacity", d => d === 100 ? 0.1 : 0.3)
.attr("stroke-width", 2)
.attr("stroke", "#ccc")
.attr("x2", width - margin.left - margin.right))
Insert cell
line = d3.line()
.defined(d => !isNaN(d))
.x((d, i) => x(data.dates[i]))
.y(d => y(d))
Insert cell
d3.timeFormatDefaultLocale(locale);
Insert cell
locale = (
{
"decimal": ",",
"thousands": ".",
"grouping": [3],
"currency": ["R$", ""],
"dateTime": "%d/%m/%Y %H:%M:%S",
"date": "%d/%m/%Y",
"time": "%H:%M:%S",
"periods": ["AM", "PM"],
"days": ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"],
"shortDays": ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"],
"months": ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
"shortMonths": ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]
}
)
Insert cell
d3 = require("d3@5", "d3-array@2")
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