Skip to content

Labeled Pie ​

A donut with three cm.label marks: the values in bold inside the wedges, black or white by the color of each wedge, and the ids just outside, with their shares on a second line. Above the center, the id goes up a line and the share takes its place, keeping both lines off the pie. After G2, without its spider lines.

js
const data = [
  {id: "c", value: 526},
  {id: "sass", value: 220},
  {id: "php", value: 325},
  {id: "elixir", value: 561},
  {id: "rust", value: 54},
];
const total = data.reduce((sum, d) => sum + d.value, 0);
const outside = {position: "outside", padding: 10, fontWeight: "bold"};

// Whether the middle of a wedge is above the center: its angle, clockwise from 12 o'clock.
const above = (d) => Math.cos((d.x + d.x1) / 2) > 0.3;

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

root
  .data(data)
  .transform(cm.encode, {x: "value", fill: "id"})
  .transform(cm.stackX)
  .transform(cm.polar, {
    innerRadius: 0.25,
    fill: {
      domain: data.map((d) => d.id),
      range: ["#e8c1a0", "#f47560", "#f1e15b", "#e8a838", "#61cdbb"],
    },
  })
  .add(cm.arc, {cornerRadius: 4, stroke: "#fff", strokeWidth: 2})
  .add(cm.label, {
    text: "value",
    position: "inside",
    padding: 14,
    fontWeight: "bold",
    contrast: true,
  })
  .add(cm.label, {...outside, text: "id", dy: (d) => (above(d) ? -12 : 0)})
  .add(cm.label, {
    ...outside,
    text: (d) => d.datum.value / total,
    format: ".0%",
    dy: (d) => (above(d) ? 0 : 12),
    fontWeight: null,
  });

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