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

dcj
  • 73
  • 4

1 Answers1

5

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

jakevdp
  • 77,104
  • 11
  • 125
  • 160
  • 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! – dcj Feb 24 '19 at 19:03
  • Further revision: month being zero-based is indeed documented behavior of date time() – dcj Feb 24 '19 at 19:38
  • 1
    Yes, month is zero-based according to the docs: https://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. – jakevdp Feb 24 '19 at 21:17