Search code examples
vega-litevega

Can you have facets & layers in single Vegalite plot?


I am struggling to understand why a layer spec like the below:

"layer": [
    {"encoding": {
        "facet": {"field": "FEATURE_VALUE"},
        "x": {
            "field": "DATE",
            "type": "temporal"
        },
        "y": {
            "field": "VALUE",
            "type": "quantitative"
        }
    },
    "mark": {
        "type": "line"
    }}
    ]

Throws an error to the effect of: Cannot read property 'push' of undefined

Meanwhile, the unit spec:

"encoding": {
        "facet": {"field": "FEATURE_VALUE"},
        "x": {
            "field": "DATE",
            "type": "temporal"
        },
        "y": {
            "field": "VALUE",
            "type": "quantitative"
        }
    },
    "mark": {
        "type": "line"
    }
}

works just fine.

I can tell this has something to do with: Altair: Can't facet layered plots

However, can't quite seem to answer the principle question: can I have a trellis plot using facet as well as have layers on top of that (for say tooltips, rulers, etc.)

Thank you!


Solution

  • Vega-Lite provides two ways to specify facets: as an encoding (See Facet, Row, and Column Encoding Channels) and as an operator (See Facet Operator).

    A layer chart is not allowed to contain a facet encoding, however a facet operator can contain a layer chart (the reason for this is that the semantics of layers containing incompatible facets is unclear).

    So, instead of something like this:

    "layer": [
        {"encoding": {
            "facet": {"field": "FEATURE_VALUE"},
            "x": {
                "field": "DATE",
                "type": "temporal"
            },
            "y": {
                "field": "VALUE",
                "type": "quantitative"
            }
        },
        "mark": {
            "type": "line"
        }}
    ]
    

    you can do something like this:

    "facet": {"field": "FEATURE_VALUE"},
    "spec": {
      "layer": [
        {"encoding": {
            "x": {
                "field": "DATE",
                "type": "temporal"
            },
            "y": {
                "field": "VALUE",
                "type": "quantitative"
            }
        },
        "mark": {
            "type": "line"
        }}
      ]
    }