addTooltips(Plot.plot({
color: {
legend: true
},
width: 1000,
style: { paddingLeft: 50, overflow: "visible" },
y: {
grid: true,
},
x: {
type: "band",
tickFormat: d => d.toLocaleString("en", {month: "narrow"}),
label: null
},
marks: [
Plot.barY(
Object.entries(categorise(await query(`
WITH monthly_transactions AS (SELECT
t.month_start,
u.*
FROM (
SELECT * FROM generate_series(
'2018-01-01'::DATE,
'2022-06-01'::DATE,
'1 month'
) AS month_start
) t
JOIN (
SELECT
"Description" AS business,
"Started Date" as ts
FROM
${tableName}
WHERE
"Type" = 'CARD_PAYMENT'
) u ON
u.ts > t.month_start AND
u.ts <= t.month_start + interval '1 month')
SELECT
month_start::DATE as month,
business,
COUNT(0)::INTEGER as purchases
FROM monthly_transactions
GROUP BY 1, 2
ORDER BY 1
`), categories)).flatMap(
([category, months]) => sumByKey(
months,
'month',
'purchases',
x => x.getTime(),
x => {return new Date(x)}
).map(
({month, purchases}) => ({month, purchases, category}))).sort(
(a, b) => a.month - b.month)
, {
order: "sum",
x: "month",
y: "purchases",
fill: "category",
title: d => `${d.month.toISOString().split('T')[0].slice(0,-3)} ${d.category}: ${d.purchases}`}),
Plot.ruleY([0])
]
}))