Search code examples
plotdata-visualizationobservablehq

In Observable Plot, how to sort/order the stack from a bin() transform?


I'm working on a stacked bar chart in Observable's new Plot library. It's not too bad coming from Vega and D3, but I cannot find or figure how to order the resulting stacked bars from the Plot.binX() I'm using.

My actual mark looks something like this today:

Plot.rectY(hourlyUsageData, Plot.binX({
      y: "sum", 
      title: bin => bin[0].Name
    }, {
      x: d => d3.timeHour.count(d3.timeDay(d.DateTime), d.DateTime),
      y: d => d.kWh,
      thresholds: 24,
      fill: "Name",
      //order: "sum",
      //reverse: true
    }))

Plot.binX() does just fine, resulting in a chart in which the stack is ordered according to the input ordering.

I'd like the stack to be ordered based on a sum, and in fact if I add the Plot.stack option for order (see commented line above), I can order by sum:

Wrongly-ordered stacked bar

Close! Now I just need to reverse the order. I hypothesize that, since I can use the order option, perhaps I can also use the reverse option (see commented line above). That doesn't seem to work.

My second hypothesis is that, since these transforms are supposed to be "composable", that I should be able to combine my binX with a stackY, but I cannot find an example of such a composition. I've tried Plot.stackY(Plot.binX({...}, { ... order:"sum", reverse:true }), and similar variations, but they don't seem to work either.

In summary, I'd love to know how to control the order of the stacks in my stacked bar chart while also using binX. Thanks!


Solution

  • Thank you. It seems that there is a bug and the {order} option is consumed for nothing by the bin transform. We'll try to fix this. In the meantime you can add it "outside" the bin transform like so:

    Plot.rectY(data,
      Plot.stackY({
        ...Plot.binX(
          { y: "count" },
          { x: "body_mass", fill: "species", order: "sum" }
        ),
        reverse: true
      })
    ).plot()
    

    Pull-request to solve this issue: https://github.com/observablehq/plot/pull/439