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

1

7

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....

Teeming answered 22/2, 2019 at 22:19 Comment(0)
C
6

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

Caper answered 23/2, 2019 at 1:48 Comment(3)
This is very helpful, thank you! Why is month 2 considered to be March instead of February? Is there a way to subtract one from the month in the calculate expression you wrote above? Revised: changing to datum.date.month - 1 works!Teeming
Further revision: month being zero-based is indeed documented behavior of date time()Teeming
Yes, month is zero-based according to the docs: vega.github.io/vega/docs/expressions/#datetime. You can change it to date.month - 1 within the calculate expression if you want to use normal 1-based months.Caper

© 2022 - 2024 — McMap. All rights reserved.