Plot.text on Plot.stackX

Not quite sure how to ask this … perhaps just link to a notebook cell?

I have a bar chart I want to label, but its made with stackX to get bar widths proportional to the X value. I’ve tried all manner of ways of labelling the height of the bar at the top of the bar … but without success.

First day using Observable … !!

Many thanks,

If I understand correctly, the problem is that the stackX transform implicitly groups by y, treating each unique value of y as a separate stack. In your case you want it all to be treated as a single stack. So you can move the y option out of the stack transform and apply it after, like so:

Plot.text(groupdata20221, {
  ...Plot.stackX({x: "Population"}),
  y: "PerCapPower",
  textAnchor: "middle",
  dy: -5,
  text:(d) => `${d.PerCapPower.toFixed(2)}`
})

I perhaps didn’t get the “…” right, but I did eventually solve the problem with { x: “x”, … not quite sure I understand this but it works!
see the difference between cells “mychart” and “mychart2”.

------------ Works …
mychart = Plot.plot({
y: {label: “Per Capita Power (watts)”},
x: {label: “Population (million)”},
marks: [
Plot.rectY(groupdata20221, Plot.stackX(
{x: “Population”, y2: “PerCapPower”, fill: “Region”,
title: (d) => ${d.Region} ${d.str}
})),
Plot.text(groupdata20221,{x: “x”,y: “PerCapPower”, textAnchor: “middle”, dy: -5,text:(d) => ${d.PerCapPower.toFixed(2)}}),
Plot.text([[4000,800]], {textAnchor: “start”,
text: d=>[Total current global power 2022: ${global} GW\n IEA NetZero by 2050 target: ${global *2.6} GW]})
]

})

---------------- Syntax error on second stackX
mychart2 = Plot.plot({
y: {label: “Per Capita Power (watts)”},
x: {label: “Population (million)”},
marks: [
Plot.rectY(groupdata20221, Plot.stackX(
{x: “Population”, y2: “PerCapPower”, fill: “Region”,
title: (d) => ${d.Region} ${d.str}
})),
Plot.text(groupdata20221,{
Plot.stackX({x: “Population”}),
y: “PerCapPower”,
textAnchor: “middle”,
dy: -5,
text:(d) => ${d.PerCapPower.toFixed(2)}
}),
Plot.text([[4000,800]], {textAnchor: “start”,
text: d=>[Total current global power 2022: ${global} GW\n IEA NetZero by 2050 target: ${global *2.6} GW]})
]