Forum Discussion

jonespossibly's avatar
jonespossibly
Advocate I
4 years ago
Solved

Another Deneb query - 2 data fields on one bar chart

I have cause to render two different data fields on to the same bars in the same chart. so for instance the x axis will be date y axis should have field 'A' and field 'B' stacked on top of each oth...
  • dm-p's avatar
    dm-p
    4 years ago

    Here's another approach, using a single legend, but using a fold transform to unpivot, and a calculate transform to assign a unique 'grouping' value that can be coloured accordingly. This solution uses a single mark also:

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "data": {
        "values": [
          {"A": 10, "B": 20, "Z": "poop", "created": "2022/01/01"},
          {"A": 10, "B": 10, "Z": "moop", "created": "2022/01/01"},
          {"A": 10, "B": 5, "Z": "doop", "created": "2022/01/01"},
          {"A": 13, "B": 12, "Z": "poop", "created": "2022/02/01"},
          {"A": 33, "B": 10, "Z": "moop", "created": "2022/02/01"},
          {"A": 0, "B": 5, "Z": "doop", "created": "2022/02/01"},
          {"A": 13, "B": 5, "Z": "poop", "created": "2022/03/01"},
          {"A": 3, "B": 2, "Z": "moop", "created": "2022/03/01"},
          {"A": 20, "B": 7, "Z": "doop", "created": "2022/03/01"}
        ]
      },
      "transform": [
        {"timeUnit": "month", "field": "created", "as": "month"},
        {"fold": ["A", "B"], "as": ["series", "value"]},
        {"calculate": "datum.series + ': ' + datum.Z", "as": "grouping"}
      ],
      "mark": "bar",
      "encoding": {
        "x": {"timeUnit": "month", "field": "created", "type": "ordinal"},
        "y": {"field": "value", "type": "quantitative"},
        "color": {"field": "grouping"}
      }
    }

    Editor link

    Regards,

    Daniel