Search code examples
vega-lite

Force order of painting, in non-stacked area chart


While working with Vega Lite, I'm unable to force the same order for painting non-stacked areas.

For example, see what happens here:

enter image description here

In the rows picture above, I expect light-blue to always be behind dark-blue. However this is not true for the 3rd, 4th, and 6th row.

I've tried several combinations of order, sort, and zrank — with no success. Any idea on how to force this?

See the sample full viz in the editor — I can't get India, Israel, or Japan to display the dark-blue area on top of the light-blue.


Solution

  • I don't think there is currently a way to control the z order of area charts from the chart spec, but you can control it via the order of the data source: the colors are stacked in the order that they appear. For example, here in row 0, color 1 comes first, and in row 1, color 0 comes first:

    {
      "data": {
        "values": [
          {"x": 0, "y": 2, "row": 0, "color": 1},
          {"x": 1, "y": 1, "row": 0, "color": 1},
          {"x": 0, "y": 1, "row": 0, "color": 0},
          {"x": 1, "y": 2, "row": 0, "color": 0},
          {"x": 0, "y": 2, "row": 1, "color": 0},
          {"x": 1, "y": 1, "row": 1, "color": 0},
          {"x": 0, "y": 1, "row": 1, "color": 1},
          {"x": 1, "y": 2, "row": 1, "color": 1}
        ]
      },
      "mark": "area",
      "encoding": {
        "x": {"field": "x", "type": "temporal"},
        "y": {"field": "y", "type": "quantitative", "stack": false},
        "color": {"field": "color", "type": "ordinal"},
        "row": {"field": "row", "type": "ordinal"}
      },
      "height": 50
    }
    

    enter image description here

    If you rearrange the rows so that color 0 appears before color 1 in both cases, the stack order on the chart will be consistent:

    {
      "data": {
        "values": [
          {"x": 0, "y": 1, "row": 0, "color": 0},
          {"x": 1, "y": 2, "row": 0, "color": 0},
          {"x": 0, "y": 2, "row": 0, "color": 1},
          {"x": 1, "y": 1, "row": 0, "color": 1},
          {"x": 0, "y": 2, "row": 1, "color": 0},
          {"x": 1, "y": 1, "row": 1, "color": 0},
          {"x": 0, "y": 1, "row": 1, "color": 1},
          {"x": 1, "y": 2, "row": 1, "color": 1}
        ]
      },
      "mark": "area",
      "encoding": {
        "x": {"field": "x", "type": "temporal"},
        "y": {"field": "y", "type": "quantitative", "stack": false},
        "color": {"field": "color", "type": "ordinal"},
        "row": {"field": "row", "type": "ordinal"}
      },
      "height": 50
    }
    

    enter image description here

    If you re-order the rows your input data by year (so all 2019 entries come before all 2020 entries), the stack order should be the same in each panel.