How to display text in each level of a stacked bar chart made with Plot

I am trying to show text in each square, in a way similar to this block:

With the following code…

Plot.plot({
  color: {
    scheme: "greys",
    reverse: true
  },
  y: {
    label: "↑ Population",
    tickFormat: "s",
    grid: true
  },
  marks: [
    Plot.barY(
      data_sortable,
      Plot.groupX(
        { y: "sum"},
        { x: "state",
         y: "population",
         fill: "ageGroup",
         sort: {x: 'y', reverse: true}
        }
      )
    ),
    // Add text to each box
    Plot.textY( data_sortable,
      Plot.groupX(
        { y: "sum", text: 'first'},
        { x: "state",
         y: "ageGroup",
         text: "ageGroup",  // <-- not the right approach
         fill: "red",  // for debugging
         sort: {x: 'y', reverse: true},
        }
      )
    )
  ],
})

…I get this result (the red labels are all on the x axis):

As an additional feature: Ideally, if a square is too small to show text, that square would not show any.

If anyone has an idea on how to accomplish this/these with Observable Plot, I would greatly appreciate hearing it. Many thanks in advance!

Here is also a notebook in which I isolated the issue with minimal code.

I’d suggest this:

    Plot.textY(
      data_sortable,
      Plot.stackY(
        Plot.groupX(
          { y: "sum", text: "first" },
          {
            x: "state",
            z: "ageGroup",
            y: "population",
            text: (d) => (d.population < 1000000 ? null : d.ageGroup),
            fill: "red" // for debugging
            //sort: {x: 'y', reverse: true},
          }
        )
      )
    )

Contrary to the bar mark, the text mark isn’t stacked by default, so we have to add Plot.stackY explicitly. Then, we want the sums to be computed for each different ageGroup, so we need to specify z: “ageGroup” (the bar mark gets z from the fill definition). Finally, a filter on population size allows to remove the labels for the smallest segments.

4 Likes

Thank you very much for the suggestion and the clear explanation! It’s good to know that stack may need to be manually added and to have better insight into how z works in the context of stacked bar charts.