Four Chords and the Truth
  • Article
  • Find your song

Find your song

Search a song or an artist and see how its harmony compares with its era

measures = [
  {key: "stm_w", name: "Chord surprise", unit: "bits per chord",
   help: "how hard the next chord is to guess from the song so far"},
  {key: "distinct_w", name: "Distinct chords", unit: "per 32-chord stretch",
   help: "how many different chords a stretch of the song uses"},
  {key: "loop_coverage", name: "Main-loop share", unit: "share of the song",
   help: "how much of the song is its most-used 4-chord loop"},
  {key: "nondiatonic_share", name: "Chords outside the key", unit: "share of chords",
   help: "borrowed, chromatic and secondary-dominant chords"},
  {key: "extended_share", name: "7th and extended chords", unit: "share of chords",
   help: "chords with a 7th or other added colour tone"},
  {key: "conv_surprisal", name: "Unusual chord moves", unit: "bits per chord",
   help: "how rare its chord moves are across all songs"}
]
numeric = new Set(["artist_id", "year", "key_low_conf", "hot100", "n_changes",
  ...measures.flatMap(m => [m.key, m.key + "_pct"])])
parseRow = d => {
  for (const k of Object.keys(d)) if (numeric.has(k)) d[k] = d[k] === "" ? NaN : +d[k];
  return d;
}
songs = d3.csvParse(await FileAttachment("explorer-data/songs.csv").text(), parseRow)
artists = d3.csvParse(await FileAttachment("explorer-data/artists.csv").text(), d => {
  for (const k of Object.keys(d)) if (k !== "artist" && k !== "genre") d[k] = +d[k];
  return d;
})
era = d3.csvParse(await FileAttachment("explorer-data/era.csv").text(), d3.autoType)
eraBy = d3.index(era, d => d.measure, d => d.year)
songsByArtist = d3.group(songs, d => d.artist_id)
viewof mode = Inputs.radio(["Song", "Artist"], {value: "Song", label: "Explore by"})
viewof query = Inputs.text({placeholder: mode === "Song" ? "Song title or artist, e.g. Let It Be"
  : "Artist name, e.g. Taylor Swift", width: 420, submit: false})
norm = s => s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "")
q = norm(query.trim())
// title without version suffixes ("- Remastered 2009", "(Live)") so "Wonderwall - Remastered"
// counts as an exact match for "wonderwall"
base = s => norm(s).replace(/\s+-\s+.*$/, "").replace(/\s*[([].*?[)\]]\s*/g, " ").trim()
rank = (text, extra) => {
  const t = base(text);
  return t === q ? 0 : t.startsWith(q) ? 1 : t.includes(q) || norm(text).includes(q) ? 2 : extra;
}
// best matches first: exact title, title starts with, title contains, then artist matches;
// ties: Hot 100 songs first, then most songs / earliest year
songMatches = q.length < 2 ? [] : songs
  .map(d => ({d, r: Math.min(rank(d.title, 9), rank(d.artist, 9) + 3)}))
  .filter(x => x.r < 9)
  .sort((a, b) => a.r - b.r || b.d.hot100 - a.d.hot100 || a.d.year - b.d.year)
  .slice(0, 300).map(x => x.d)
artistMatches = q.length < 2 ? [] : artists
  .map(d => ({d, r: rank(d.artist, 9)})).filter(x => x.r < 9)
  .sort((a, b) => a.r - b.r || b.d.n_songs - a.d.n_songs)
  .slice(0, 100).map(x => x.d)
clickable = view => {
  view.addEventListener("click", e => {
    const tr = e.target.closest("tbody tr");
    if (!tr || e.target.tagName === "INPUT") return;
    tr.querySelector("input")?.click();
  });
  view.classList.add("pick-table");
  return view;
}
viewof picked = clickable(mode === "Song"
  ? Inputs.table(songMatches, {columns: ["title", "artist", "year", "genre"],
      header: {title: "Title", artist: "Artist", year: "Year", genre: "Genre"},
      format: {year: d => String(d)}, multiple: false, required: false, rows: 8,
      width: {title: 360, artist: 240}})
  : Inputs.table(artistMatches, {columns: ["artist", "n_songs", "year_min", "year_max", "genre"],
      header: {artist: "Artist", n_songs: "Songs", year_min: "From", year_max: "To", genre: "Genre"},
      format: {year_min: d => String(d), year_max: d => String(d)},
      multiple: false, required: false, rows: 8}))
nMatch = (mode === "Song" ? songMatches : artistMatches).length
hint = q.length < 2
  ? html`<p class="note">Type at least two letters. ${songs.length.toLocaleString()} songs by
      ${artists.length.toLocaleString()} artists, 1955–2022.</p>`
  : picked == null ? html`<p class="note">${nMatch} ${nMatch === 1 ? "match" : "matches"}${(mode === "Song" ? songMatches.length === 300 : artistMatches.length === 100)
      ? " (first ones shown; type more to narrow)" : ""}. Click a row.</p>` : html``
fmt = (m, v) => m.unit.startsWith("share") ? `${Math.round(v * 100)}%` : v.toFixed(2)
eraLabel = y => `${Math.max(1955, y - 2)}–${Math.min(2022, y + 2)}`

function strip(m, value, pct, year, label) {
  const e = eraBy.get(m.key).get(year);
  const x = Plot.plot({
    width: 520, height: 46, marginLeft: 10, marginRight: 30,
    x: {domain: d3.extent([e.p5, e.p95, value]), label: null, ticks: 4,
        tickFormat: m.unit.startsWith("share") ? (d => `${Math.round(d * 100)}%`) : (d => d.toFixed(1))},
    y: {axis: null, domain: [0, 1]},
    marks: [
      Plot.ruleY([0.5], {x1: e.p5, x2: e.p95, stroke: "#c3c2b7", strokeWidth: 2}),
      Plot.rect([e], {x1: "p25", x2: "p75", y1: 0.25, y2: 0.75, fill: "#cce3fd"}),
      Plot.tickX([e], {x: "p50", y1: 0.2, y2: 0.8, stroke: "#2a78d6", strokeWidth: 2}),
      Plot.dot([{v: value}], {x: "v", y: 0.5, r: 7, fill: "#eb6834", stroke: "white",
        strokeWidth: 2, title: d => `${label}: ${fmt(m, d.v)}`})
    ]
  });
  return html`<div class="measure-row">
    <div class="measure-name"><b>${m.name}</b> ${fmt(m, value)}
      <small>${m.help}</small>
      <small>higher than ${Math.round(pct)}% of songs from ${eraLabel(year)}</small></div>
    <div>${x}</div></div>`;
}

function chips(loop) {
  if (!loop) return html`<span class="note">no repeating 4-chord loop found</span>`;
  return html`<div class="chips">${loop.split("–").map(c => html`<span class="chip">${c}</span>`)}</div>`;
}

function topChords(top) {
  const rows = (top || "").split("|").filter(Boolean).map(s => {
    const i = s.lastIndexOf(" ");
    return {chord: s.slice(0, i), pct: +s.slice(i + 1)};
  });
  return Plot.plot({
    width: 380, height: 30 + rows.length * 24, marginLeft: 70, marginRight: 40,
    x: {label: "% of chord changes", grid: true}, y: {label: null, domain: rows.map(d => d.chord)},
    marks: [Plot.barX(rows, {x: "pct", y: "chord", fill: "#2a78d6"}),
            Plot.text(rows, {x: "pct", y: "chord", text: d => `${d.pct}%`, dx: 14, fill: "#52514e"}),
            Plot.ruleX([0])]
  });
}

function eraChart(points, title) {
  const e = era.filter(d => d.measure === "stm_w");
  return Plot.plot({
    width: 820, height: 280, marginLeft: 50,
    x: {label: "Release year", tickFormat: d => String(d)},
    y: {label: "Chord surprise (bits per chord)", grid: true},
    marks: [
      Plot.areaY(e, {x: "year", y1: "p25", y2: "p75", fill: "#cce3fd", fillOpacity: 0.8}),
      Plot.line(e, {x: "year", y: "p50", stroke: "#2a78d6", strokeWidth: 2}),
      Plot.dot(points, {x: "year", y: "stm_w", r: 5, fill: "#eb6834", stroke: "white",
        title: d => `${d.title} (${d.year}): ${d.stm_w.toFixed(2)}`, tip: true}),
      Plot.text([{x: 1956, y: e[1].p50}], {x: "x", y: "y", text: () => "middle song of its era",
        dy: -10, textAnchor: "start", fill: "#52514e"})
    ],
    caption: title
  });
}
card = {
  if (picked == null) return html``;
  if (mode === "Song") {
    const s = picked;
    return html`<div class="song-card">
      <h2>${s.title}</h2>
      <div class="meta">${s.artist} · ${s.year} · ${s.genre} · estimated key ${s.key}${
        s.key_low_conf ? html`<span class="badge-hs">key uncertain</span>` : ""}${
        s.hot100 ? html`<span class="badge-hs">Billboard Hot 100</span>` : ""}</div>
      <div style="display:flex; gap:3rem; flex-wrap:wrap; margin-top:1rem">
        <div><b>Main 4-chord loop</b> <span class="note">(Roman numerals in its key)</span>
          ${chips(s.loop)}
          <span class="note">covers ${Math.round(s.loop_coverage * 100)}% of its chord changes</span></div>
        <div><b>Most-used chords</b>${topChords(s.top)}</div>
      </div>
      <h4 style="margin-top:1rem">Compared with songs from ${eraLabel(s.year)}</h4>
      <p class="note">Grey line: middle 90% of songs from those years; blue box: middle half;
        blue tick: the middle song; orange dot: this song.</p>
      ${measures.map(m => strip(m, s[m.key], s[m.key + "_pct"], s.year, s.title))}
      ${eraChart([s], "Orange dot: this song. Blue: the middle song of each era, with the middle half shaded.")}
    </div>`;
  }
  const a = picked;
  const list = songsByArtist.get(a.artist_id) || [];
  return html`<div class="song-card">
    <h2>${a.artist}</h2>
    <div class="meta">${a.n_songs} songs · ${a.year_min}–${a.year_max} · ${a.genre}${
      a.hot100_songs ? html`<span class="badge-hs">${a.hot100_songs} on the Hot 100</span>` : ""}</div>
    <h4 style="margin-top:1rem">Average across the artist's songs</h4>
    <p class="note">Each measure is the artist's average, drawn against songs from around their
      median year (${a.year_median}); the percentile is the average of their songs' percentiles.</p>
    ${measures.map(m => strip(m, a[m.key], a[m.key + "_pct"], a.year_median, a.artist))}
    ${eraChart(list, `Each orange dot is one of ${a.artist}'s songs.`)}
    <h4>Songs</h4>
    ${Inputs.table(list, {columns: ["title", "year", "loop", "stm_w", "stm_w_pct"],
       header: {title: "Title", year: "Year", loop: "Main loop", stm_w: "Chord surprise",
                stm_w_pct: "Percentile in its era"},
       format: {year: d => String(d), stm_w: d => d.toFixed(2)}, rows: 12})}
  </div>`;
}

About the data. Chord charts come from the Chordonomicon dataset (user-submitted tabs; CC BY-NC 4.0). Song titles come from Spotify and artist names from MusicBrainz. Release years are corrected with MusicBrainz and the Billboard Hot 100. Keys are estimated from the chords, so one song in five carries an “uncertain” key. To respect the data licence, the explorer shows each song’s main loop and most-used chords, not its full chord chart. Simpler is not worse: the measures describe harmony, not quality.