Vega-lite Stacked bar chart with 2 different data objects

Im trying to emulate in Vega lite the behaviour of power BI where if you add 2 data objects based along the same date, you're able to stack the data on top of each other.

I'm using Deneb in power BI, but it uses vega lite, so any vega lite solution should be fine.

i have a data set of counts before today and a dataset of counts after today. I want to combine them so that if before today and after today have data in the same month then they are stacked rather than overlaying each other.

I can't seem to find a solution that doesn't involve grouping the data into one object

Upvotes: 1

Views: 1194

Answers (1)

jakevdp
jakevdp

Reputation: 86453

The way to combine two datasets into a single stacked bar chart is to make use of a lookup transform to join the datasets together. If you want to then stack bars from different columns, you can use a fold transform to combine them before doing a standard bar chart.

For example (open in vega editor):

{
  "datasets": {
    "table-1": [
      {"key": "A", "A": 2},
      {"key": "B", "A": 3},
      {"key": "C", "A": 1},
      {"key": "D", "A": 2}
    ],
    "table-2": [
      {"key": "A", "B": 6},
      {"key": "B", "B": 4},
      {"key": "C", "B": 1},
      {"key": "D", "B": 3}
    ]
  },
  "data": {"name": "table-1"},
  "transform": [
    {
      "lookup": "key",
      "from": {"data": {"name": "table-2"}, "key": "key", "fields": ["B"]}
    },
    {"fold": ["A", "B"], "as": ["column", "value"]}
  ],
  "mark": "bar",
  "encoding": {
    "color": {"field": "column", "type": "nominal"},
    "x": {"field": "value", "type": "quantitative"},
    "y": {"field": "key", "type": "nominal"}
  }
}

enter image description here

Upvotes: 2

Related Questions