Skip to content

add chess bump chart example #652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ jobs:
'examples/*/yarn.lock'
- run: yarn --frozen-lockfile
- run: yarn build
- name: Build example "chess"
run: yarn --frozen-lockfile && yarn build
working-directory: examples/chess
- name: Build example "google-analytics"
run: yarn --frozen-lockfile && yarn build
working-directory: examples/google-analytics
Expand Down
71 changes: 71 additions & 0 deletions examples/chess/docs/data/top-ranked-players.json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import {utcMonth} from "d3-time";
import JSZip from "jszip";

const TOP_N_COUNT = 10;
const MONTHS_OF_DATA = 12;

function monthlyZipUrl(date) {
const id = date
.toLocaleString("en-US", {
month: "short",
year: "2-digit"
})
.toLowerCase()
.replace(" ", "");
return `http://ratings.fide.com/download/standard_${id}frl.zip`;
}

async function fetchAndFilterTopPlayers() {
const today = utcMonth();
const rankingsByMonth = await Promise.all(
utcMonth
.range(utcMonth.offset(today, -11), utcMonth.offset(today, 1))
.map((month) =>
fetchFideData(monthlyZipUrl(month)).then((rows) =>
rows.sort((a, b) => b.rating - a.rating).map((d) => ({...d, month}))
)
)
);

// top active women
const womens = rankingsByMonth
.map((rankings) => rankings.filter((d) => d.sex === "F" && d.flags !== "wi").slice(0, TOP_N_COUNT))
.flat();

// top active men
const mens = rankingsByMonth
.map((rankings) => rankings.filter((d) => d.sex === "M" && d.flags !== "i").slice(0, TOP_N_COUNT))
.flat();

return {womens, mens, MONTHS_OF_DATA, TOP_N_COUNT};
}

async function fetchFideData(url) {
return fetch(url)
.then((res) => JSZip.loadAsync(res.arrayBuffer()))
.then((archive) => archive.file(Object.keys(archive.files).find((name) => name.endsWith(".txt"))).async("text"))
.then(parseFideFile);
}

function parseFideFile(text) {
return text
.split("\n")
.slice(1) // skip header row
.map((line) => ({
id: line.substring(0, 14).trim(),
name: line.substring(15, 75).trim(),
federation: line.substring(76, 79).trim(),
sex: line.substring(80, 83).trim(),
title: line.substring(84, 88).trim(),
// wtit: line.substring(89, 93).trim(),
// otit: line.substring(94, 108).trim(),
// foa: line.substring(109, 112).trim(),
rating: +line.substring(113, 118).trim(),
// games: +line.substring(119, 122).trim(),
// ratingKFactor: +line.substring(123, 125).trim(),
born: +line.substring(126, 131).trim(),
flags: line.substring(132, 136).trim()
}));
}

console.log(JSON.stringify(await fetchAndFilterTopPlayers()));
129 changes: 129 additions & 0 deletions examples/chess/docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
---
toc: false
theme: dashboard
---

# A Year of Chess Rankings

Rankings of the top ${TOP_N_COUNT} players of _standard_ chess in the last ${MONTHS_OF_DATA} months. Data: [FIDE](https://ratings.fide.com/)

```js
const { womens, mens, MONTHS_OF_DATA, TOP_N_COUNT } = await FileAttachment("data/top-ranked-players.json").json();
const titleMap = {
"GM": "Grand Master",
"WGM": "Womens Grand Master"
};
const darkScheme = Generators.observe((change) => {
const mm = window.matchMedia?.('(prefers-color-scheme: dark)');
if (!mm) return change("lighten");
change(mm.matches);
mm.addEventListener("change", () => change(mm.matches));
});
```

```js
function bumpMarks(data, { r = 3, curve = "bump-x", ...options }, [firstMonth, lastMonth]) {
options = Plot.stackY2(options);
options.y.label = "rank";
return Plot.marks(
Plot.lineY(data, Plot.binX({x: "first", y: "first", filter: null}, {
...options,
stroke: options.z,
curve,
fill: null,
mixBlendMode: darkScheme ? "lighten" : "darken",
interval: "month"
})),
Plot.text(data, { ...options, text: options.y, fill: "black" }),
Plot.text(
data.filter(d => d.month === lastMonth),
Plot.selectFirst({
...options,
text: options.z,
dy: 0,
dx: 10 + (r || options.strokeWidth / 2),
textAnchor: "start",
fill: "currentColor",
}),
),
Plot.text(
data.filter(d => d.month === firstMonth),
Plot.selectLast({
...options,
text: options.z,
dy: 0,
dx: -(10 + (r || options.strokeWidth / 2)),
textAnchor: "end",
fill: "currentColor"
})
)
);
}

function bumpChart(data, width) {
const months = [...new Set(data.map(d => d.month))].sort();
const tickFormat = dateString => {
const date = new Date(dateString);
return d3.utcFormat(date.getMonth() === 0 ? "%b %y" : "%b")(date);
}

return Plot.plot({
marginTop: 20,
marginBottom: 35,
marginLeft: 125,
marginRight: 125,
width,
x: {
domain: months,
tickFormat,
label: null,
grid: true
},
y: {
axis: null,
domain: [10.5, 1]
},
color: {
domain: d3
.groupSort(
data,
(v) => v[0].rating,
(d) => d.name
)
.reverse()
},
marks: [
bumpMarks(data, {
x: "month",
z: "name",
order: "rating",
reverse: true,
strokeWidth: 24,
strokeLinejoin: "round",
strokeLinecap: "round",
r: 0,
dy: ".35em",
fill: "white",
tip: true,
channels: {rating: "rating"},
title: (d) => `name: ${d.name}\ntitle: ${titleMap[d.title] ?? ""}\nborn: ${d.born}\nrating: ${d.rating}\nfederation: ${d.federation}\nmonth: ${d3.utcFormat("%b %y")(new Date(d.month))}`,
href: ({ id }) => `https://ratings.fide.com/profile/${id}`,
target: "_blank"
}, [months.at(0), months.at(-1)])
]
})
}
```

<div class="grid">
<div class="card">
<h1>Womens</h1>
${resize((width) => bumpChart(womens, width))}
</div>
<div class="card">
<h1>Mens</h1>
${resize((width) => bumpChart(mens, width))}
</div>
</div>

_Data from the [International Chess Federation](https://ratings.fide.com/)._
17 changes: 17 additions & 0 deletions examples/chess/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"type": "module",
"scripts": {
"dev": "observable preview",
"build": "rm -rf dist && observable build",
"postinstall": "ln -sf ../../../../bin/observable-init.js node_modules/.bin/observable"
},
"dependencies": {
"@observablehq/cli": "link:../..",
"d3-fetch": "^3.0.1",
"d3-time-format": "^4.1.0",
"jszip": "^3.10.1"
},
"engines": {
"node": ">=20.6"
}
}
Loading