Search code examples
d3.jsvegavega-lite

vega-lite: how to specify date in JSON as separate fields containing year, month, and day numbers?


My JSON data is a list of objects, each object contains the date in this format:

  "date" : {
    "year" : 2019,
    "month" : 2,
    "day" : 17
  },

How can I tell Vega-lite that this is a date? I have worked around this by creating another day field that is a string concatenating these three fields, and using:

    "format" : {
      "parse" : {
        "day" : "date: '%Y %m %d'"
      }

But I'd like to be able to just use the existing 3 fields....


Solution

  • You can do this with a calculate transform, along with the datetime expression. For example (vega-editor link):

    {
      "data": {
        "values": [
          {"date": {"year": 2019, "month": 2, "day": 15}, "val": 1},
          {"date": {"year": 2019, "month": 2, "day": 16}, "val": 2},
          {"date": {"year": 2019, "month": 2, "day": 17}, "val": 4},
          {"date": {"year": 2019, "month": 2, "day": 18}, "val": 3},
          {"date": {"year": 2019, "month": 2, "day": 19}, "val": 5},
          {"date": {"year": 2019, "month": 2, "day": 20}, "val": 6}
        ]
      },
      "transform": [
        {
          "calculate": "datetime(datum.date.year, datum.date.month, datum.date.day)",
          "as": "combined"
        }
      ],
      "mark": "area",
      "encoding": {
        "x": {"field": "combined", "type": "temporal"},
        "y": {"field": "val", "type": "quantitative"}
      }
    }
    

    enter image description here