Search code examples
vega-lite

Use data as arrays instead of table for Vega Lite


How to use array data in VegaLite?

I want to use data as arrays

dates   = [1, 2, 3]
prices1 = [1, 2, 1]
prices2 = [1.5, 1, 2]

Instead of the table data that's traditionally used in VegaLite

[
  { "date": 1, "price": 1, "symbol": 1 },
  { "date": 2, "price": 2, "symbol": 1 },
  { "date": 3, "price": 1, "symbol": 1 },

  { "date": 1, "price": 1.5, "symbol": 2 },
  { "date": 2, "price": 1,   "symbol": 2 },
  { "date": 3, "price": 2,   "symbol": 2 }
]

Full example with playground

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Stock prices of 5 Tech Companies over Time.",
  "data": {
    "values": [
      { "date": 1, "price": 1, "symbol": 1 },
      { "date": 2, "price": 2, "symbol": 1 },
      { "date": 3, "price": 1, "symbol": 1 },

      { "date": 1, "price": 1.5, "symbol": 2 },
      { "date": 2, "price": 1,   "symbol": 2 },
      { "date": 3, "price": 2,   "symbol": 2 }
    ]
  },
  "mark": {
    "type": "line",
    "point": {
      "filled": false,
      "fill": "white"
    }
  },
  "encoding": {
    "x": {"field": "date", "type": "quantitative"},
    "y": {"field": "price", "type": "quantitative"},
    "color": {"field": "symbol", "type": "nominal"}
  }
}

Solution

  • You can achieve this using a sequence of data transforms:

    1. A Flatten transform to turn arrays of data into normal table entries
    2. A Fold transform to convert the two price columns into a single price column with a column of labels
    3. A Calculate transform using an appropriate Vega Expression to extract the number from your price label.

    The result is something like this:

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
      "description": "Stock prices of 5 Tech Companies over Time.",
      "data": {
        "values": [
          {"date": [1, 2, 3], "prices1": [1, 2, 1], "prices2": [1.5, 1, 2]}
        ]
      },
      "transform": [
        {"flatten": ["date", "prices1", "prices2"]},
        {"fold": ["prices1", "prices2"], "as": ["symbol", "price"]},
        {"calculate": "slice(datum.symbol, -1)", "as": "symbol"}
      ],
      "mark": {"type": "line", "point": {"filled": false, "fill": "white"}},
      "encoding": {
        "x": {"field": "date", "type": "quantitative"},
        "y": {"field": "price", "type": "quantitative"},
        "color": {"field": "symbol", "type": "nominal"}
      }
    }
    

    enter image description here

    To explore what the transforms are doing, it can be useful to open the chart in the Vega Editor and use the Data Viewer tab to explore how each transform modifies the underlying data.