Public
Edited
Aug 15, 2023
1 star
Insert cell
Insert cell
Insert cell
Plot.plot({
y: { grid: true },
color: { legend: true },
marks: [
Plot.rectY(
crimea,
// Plot.stackY( // not sure why this doesn't work 🤔
{
x: "date",
y: "deaths",
interval: d3.utcMonth.every(4),
fill: "cause",
tip: true
}
// )
),
Plot.ruleY([0])
]
})
Insert cell
Insert cell
Plot.plot({
y: { grid: true },
color: { legend: true },
marks: [
Plot.rectY(
crimea,
Plot.stackY( // Plot.rectY calls Plot.stackY implicitly, so this is not required
Plot.binX(
{ y: "sum" },
{
x: "date",
y: "deaths",
interval: d3.utcMonth.every(4),
fill: "cause",
tip: true
}
)
)
),
Plot.ruleY([0])
]
})
Insert cell
Insert cell
{
const stackedValues = Plot.rectY(
crimea,
Plot.stackY(
Plot.binX(
{ y: "sum" },
{
x: "date",
y: "deaths",
interval: d3.utcMonth.every(4),
fill: "cause"
}
)
)
).initialize().channels;

return d3
.range(stackedValues.fill.value.length)
.map((d, i) => {
return {
cause: stackedValues.fill.value[i],
from: stackedValues.x1.value[i],
to: stackedValues.x2.value[i],
deaths: stackedValues.y2.value[i] - stackedValues.y1.value[i]
};
})
.sort((a, b) => d3.ascending(a.from, b.from));
}
Insert cell
Insert cell
d3
.bin()
.value((d) => d.date)
.thresholds(
d3.utcMonths(
d3.utcMonth.every(4).floor(d3.min(crimea, (d) => d.date)), // new Date("1854-01-01")
d3.max(crimea, (d) => d.date),
4 // every 4 months
)
)(crimea)
.flatMap((g) => {
return d3
.groups(g, (d) => d.cause)
.map(([cause, g2]) => ({
cause,
from: g.x0,
to: g.x1,
deaths: d3.sum(g2, (d) => d.deaths)
}));
})
Insert cell
Insert cell
{
const deathsByCauseAndMonth = d3.rollups(
crimea,
(v) => d3.sum(v, (d) => d.deaths),
(d) => d.cause,
(d) => d3.utcMonth(d.date)
);

const thresholds = d3.utcMonths(
d3.utcMonth.every(4).floor(d3.min(crimea, (d) => d.date)), // new Date("1854-01-01")
d3.max(crimea, (d) => d.date),
4 // every 4 months
);

return thresholds.flatMap((from, i) => {
const to =
i === thresholds.length - 1
? d3.utcMonth.offset(from, 4)
: thresholds[i + 1];
return deathsByCauseAndMonth.map(([cause, g]) => {
return {
cause,
from: from,
to: to,
deaths: d3.sum(
g.filter(([date, deaths]) => date >= from && date < to),
(d) => d[1]
)
};
});
});
}
Insert cell
Insert cell
Insert cell
crimea
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
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