Observable Plot: Stack and Facet

Hi there,

I’m new to Observable Plot (and js) and could not find a similar question in the community help topics for this. I am trying to create a chart that displays stacked values over time and facet that by an additional category. The resulting chart is duplicating the values for both of the fy channels.

I’ve been reading the documentation for stack, bin & group but I’m not able to figure it out, I believe I might have to group the data before binning (?). Below is the code snippet and a link to the notebook:

Plot.plot({
  facet: {
    data: data.filter(d => d.country == 'US' || d.country == 'CA'),
    y: 'country'
  },
  marks: [
    Plot.rectY(
      data.filter(d => d.country == 'US' || d.country == 'CA'),
      Plot.binX(
        { y: "count" },
        {
          x: "date",
          y: "price_in_usd",
          fill: "brand",
          thresholds: d3.utcDay
        }
      )
    )
  ],
  marginLeft: 100,
  width: 666,
  height: 300
})

The default behavior is facet: auto, which tests for strict equality and filtering returns a shallow copy of the data.

Try saving the original data to its own variable first:

{
  const data2 = data.filter((d) => d.country == "US" || d.country == "CA");
  return Plot.plot({
    facet: {
      data: data2,
      y: "country"
    },
    marks: [
      Plot.rectY(
        data2,
        Plot.binX(
          { y: "count" },
          {
            x: "date",
            y: "price_in_usd",
            fill: "brand",
            thresholds: d3.utcDay
          }
        )
      )
    ],
    marginLeft: 100,
    width: 666,
    height: 300
  });
}

The alternative is to manually specify facet: "include" or “exclude”.

1 Like