🏠 back to Observable

Adding Plot text mark for n value (sum/count) of each facet

Hi -
I need to add a text mark showing the sum or count represented for each bar in faceted stacked bars. For example, in Stack Transform / Observable Plot / Observable / Observable, I would want a text mark to the right of each bar saying something like n = 1000 or (1000 people total) indicating the number of people represented by each bar.

Thanks for any help!

use text: "count" instead of text: "first"?

or, with a function reducer:

  height: 280,
  x: {
    percent: true
  facet: {
    data: congress,
    y: (d) => Math.floor((2021 - d.birth) / 10) * 10
  marks: [
      Plot.stackX(Plot.groupZ({ x: "proportion-facet" }, { fill: "gender" }))
          { x: "proportion-facet", text: (d) => `${d[0].gender}: ${d.length}` },
          { z: "gender" }
    Plot.ruleX([0, 1])

Thanks! That makes sense, and I might end up using that instead of what I was thinking.

My idea was to display the total for the whole bar (so M + F) to the right of each bar and outside of the bar area (e.g., 24 for the top bar in the example). I see from your example how I can get grouped or overall totals. The issue I can’t seem to resolve is how to place the text mark at the end of the bar.

The end of an horizontal bar is given either by stackX1 or stackX2, depending on which end you’re considering :slight_smile:


Thanks! Per your suggestion, I changed the text mark in the example to:
Plot.text(congress,{dx: “1em”, …Plot.stackX2(Plot.groupZ({x: “proportion-facet”, text: “count”}))})
which does exactly what I want.

Just realized that this is more idiomatic (without the spread):
Plot.text(congress,Plot.stackX2(Plot.groupZ({x: “proportion-facet”, text: “count”}, {dx: “1em”})))

1 Like