Skip to content

Labeled Bars ​

Letter frequencies, each bar labeled at its end: in white inside the bars that have room, and past the end of the others. Plot draws these with two text marks; one cm.label does it, with a position and a fill per row. After Observable Plot's horizontal bar chart of letter frequencies.

js
const alphabet = await d3.csv("/data/alphabet.csv", d3.autoType);
const room = (d) => d.datum.frequency >= 0.02;

const renderer = cm.svg({width: 640, height: 560});
const root = cm.flow().renderer(renderer);

root
  .data(alphabet)
  .transform(cm.encode, {x: "frequency", y: "letter"})
  .transform(cm.spreadY, {sort: "-x"})
  .transform(cm.plane, {x: {label: "Frequency", tickFormat: "%"}, y: {label: null}})
  .add(cm.rect, {fill: "steelblue"})
  .add(cm.label, {
    text: "frequency",
    format: ".1%",
    position: (d) => (room(d) ? "inside-right" : "right"),
    fill: (d) => (room(d) ? "white" : "currentColor"),
  });

root.render();
document.body.append(renderer.node());