Search code examples
jsonvega-lite

Referencing to an Array inside of Object


There is following data Object:

{
  "station": {
    "id": {"name": "SNK"},
    "position": {"lat":0.00,"lon":0.00}
  },
  "datagram": [
    {
      "date": {"iso-8601": "1966-01-12"},
      "air": {
        "temp": {"mean": -17.8}
      },
      "precip": {"1d": 1}
    }
  ]
}

Data in question are inside of "datagram" array, and they are:

  • date.iso-8601,
  • air.temp.mean

So, is needed to indicate directly Array as data source.

I tried Transform with Calculate to create a new 'd' array:
(spec fragment)

data: {
  url: 'http://...',
  format: {type: 'json'}
},
transform: [
  {calculate: "datum.datagram", "as": "d"}
],
encoding: {
  x: {type: 'temporal', field: 'd.date.iso_date_time', title: 'Date'},
  y: {type: 'quantitative', field: 'd.air.temp.mean', title: '[°C]'}
}

It not work:

vega@5.22.1:1 WARN Infinite extent for field "d.date.iso_date_time": [Infinity, -Infinity]

The Question is: How in general I should deal, in vanilla Vega-Lite, with extracting data table from an object?

Complete spec:

{
$schema: 'https://vega.github.io/schema/vega-lite/v5.json',
description: '',
width: 'container',
  data: {
      url:'',
      format: {type: 'json'}
  },
  transform: [
    {calculate: "datum.datagram", "as": "d"}
  ],
  mark: 'circle',
  encoding: {
     x: {type: 'temporal', field: 'd.time.iso_date_time', title: 'Date'},
     y: {type: 'quantitative', field: 'd.air.temp.mean', title: '[°C]'}
  }
};

[EDIT]

Long Term Vanilla JS Solution

In this case, One can directly assign data Array outside the Vega-Lite, without invoking Calculate and Flattening:

 var vegaLiteSpec = {
   $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
   // define data as with no values at all:
   data: {values: []},
   // ...here is the rest of configuration...
 };


 fetch('https://...')
   .then(res => res.json())
   .then((out) => {
     vegaLiteSpec.data.values = out.datagram;
     vegaEmbed('#div-chartElement', vegaLiteSpec);
   })
   .catch(err => {
     throw err
   });


Solution

  • Here is an example.

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "data": {
        "values": [
          {
            "station": {"id": {"name": "SNK"}, "position": {"lat": 0, "lon": 0}},
            "datagram": [
              {
                "date": {"iso-8601": "1966-01-12"},
                "air": {"temp": {"mean": -17.8}},
                "precip": {"1d": 1}
              }
            ]
          }
        ]
      },
      "transform": [
        {"calculate": "datum.datagram", "as": "d"},
        {"flatten": ["d"]},
        {"calculate": "datum.d.date['iso-8601']", "as": "x"},
          {"calculate": "datum.d.air.temp.mean", "as": "y"}
      ],
      "mark": "point",
      "encoding": {
        "x": {"field": "x", "type": "ordinal"},
        "y": {"field": "y", "type": "quantitative"}
      }
    }
    

    enter image description here